亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

防止在 React 中提交時刷新頁面

防止在 React 中提交時刷新頁面

飲歌長嘯 2022-11-03 15:09:14
我正在嘗試創建一個可編輯的表格,該表格將在單擊特定單元格后將其轉換為一個<input>,然后handleSubmit()在用戶按下返回后運行該方法。下面是一個單元格的示例,該<td>單元格使用onClick事件運行handleClick()方法并將其轉換<td></td>為<form><input></input></form>.<td onClick={ e => this.handleClick(e)} style={{padding:'5px'}} key={cellID} id={cellID}>{frame.rows[i][idx]}</td>       handleClick(e:React.MouseEvent<HTMLTableDataCellElement, MouseEvent>) {    if(this.state.editing == false){                let form = `<form onSubmit=${ (e:any) => {this.handleSubmit(e)} } ><input type="text" value=${e.currentTarget.innerText} className="input-small gf-form-input width-auto"/></form>`      e.currentTarget.innerHTML =  form;             }           this.setState({editing: true})  } handleSubmit(e){    e.preventDefault()          }在這種情況下,使用 e.preventDefault() 似乎不起作用。每次更改文本后按回車鍵,頁面都會刷新。在這種情況下如何阻止頁面刷新?
查看完整描述

3 回答

?
素胚勾勒不出你

TA貢獻1827條經驗 獲得超9個贊

我猜你想要實現一些東西,你可以編輯列,修改或放棄更改,然后根據需要更新內容。


這個例子是本地狀態,但你仍然可以通過獲取數據來做到這一點。


單擊下面的“運行代碼片段”以查看工作示例。


// main.js


const { useState } = React;


const App = () => {

  // State

  const [data, setData] = useState([{ id: 1, name: 'John', editing: false }, { id: 2, name: 'Kevin', editing: false }]);

   

  // Functions

  const onSubmitForm = index => event => {

    // To prevent form submission

    event.preventDefault();

    // To prevent td onClick

    event.stopPropagation();

    

    const newData = [...data];

    newData[index].name = newData[index].temp;

    newData[index].editing = false;

    delete newData[index].temp;

    setData(newData);

  }

  

  const onClickToggleEditing = index => event => {

    // To prevent td onClick and button conflicting with each other for toggling back on

    event.stopPropagation();

    

    const newData = [...data];

    newData[index].editing = !newData[index].editing;

    newData[index].temp = newData[index].name;

    setData(newData);

  }

  

  const onInputChange = index => event => {

    const newData = [...data];

    newData[index].temp = event.target.value;

    setData(newData);    

  }

   

  // Render

  // This basically like having its own component

  const editing = ( data, index, onChange, onSubmit, onCancel) => {  

    const onKeyUp = index => event => {

       if (event.key === 'Escape') {

        onCancel(index)(event);

       }

    }

  

    return <form onSubmit={onSubmit(index)}><input onKeyUp={onKeyUp(index)} onClick={e => e.stopPropagation()} type="text" value={data.temp} placeholder="Enter text" onChange={onChange(index)} /><button onClick={onSubmit(index)} type="submit">Save</button><button type="button" onClick={onCancel(index)}>Cancel</button></form>

  }

  

  return <main>

    <h1>Table Editing</h1>

    <p><small>Click to edit cell for <b>Name</b>.</small></p>

    <table>

      <thead>

        <tr>

        <th>ID</th>

        <th>Name</th>

        </tr>

      </thead>

        {data && data.length > 0 && <tbody>

           {data.map((i, k) => <tr key={`row-${k}`}>

            <td>{i.id}</td>

            <td className="editable" onClick={onClickToggleEditing(k)}>{i.editing ? editing(i, k, onInputChange, onSubmitForm, onClickToggleEditing) : i.name}</td>

          </tr>)}

      </tbody>}

    </table>

    

    <hr />

    <p><b>Data Manipulation:</b></p>

    <pre><code>{JSON.stringify(data, null, '\t')}</code></pre>

    

  </main>

}


ReactDOM.render(<App />, document.querySelector('#root'));

body {

  padding: 0;

  margin: 0;

  font-family: Arial,sans-serif;

}


main {

  padding: 0 20px;

}


h1 {

  font-size: 18px;

}



table {

  width: 100%;

  border-spacing: 0;

}


table tr td,

table tr th {

  border: 1px solid #efefef;

  height: 30px;

  line-height: 30px;

  text-align: left;

  padding: 6px;

}


table tr th:first-child {

  width: 100px;

}


.editable:hover {

  background: #efefef;

  cursor: pointer;

}


table input {

  height: 30px;

  line-height: 30px;

  font-size: 14px;

  padding: 0 6px;

  margin-right: 6px;

}


table button {

  height: 32px;

  border: none;

  background: red;

  color: white;

  font-size: 14px;

  padding: 0 10px;

  border-radius: 4px;

  margin-right: 5px;

  cursor: pointer;

}


table button[type=submit] {

  height: 32px;

  border: none;

  background: green;

  color: white;

  font-size: 14px;

  padding: 0 10px;

  border-radius: 4px;

}


hr {

  border: none;

  height: 1px;

  background: #999;

  margin: 20px 0;

}


pre {

  background: #efefef;

  padding: 6px;

}

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script>

<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script>



<div id="root"></div>


查看完整回答
反對 回復 2022-11-03
?
30秒到達戰場

TA貢獻1828條經驗 獲得超6個贊

您的代碼中有一些問題。我最好修復它們,而不是嘗試解決表單提交的問題。一旦完成,您將不必解決表單的問題 - 根本不會有任何問題。


首先,讓我們看一下您的可編輯單元格:


<td onClick={ e => this.handleClick(e)} style={{padding:'5px'}} key={cellID} id={cellID}>{frame.rows[i][idx]}</td>

這個元素應該根據某些狀態以不同的方式呈現。我們可以使用 React 輕松實現這一點:


// JSX snippet

<td onClick={ e => this.handleClick(e)} 

    style={{padding:'5px'}} 

    key={cellID} id={cellID}>

    {this.state.editing ? <Input ... /> : <Label ... />}

</td>

我沒有提供所有代碼,因為我相信這些組件是不言自明的(歡迎您隨意命名它們,我給它們起非常簡單的名稱以明確其目標)。


<Input />封裝了與編輯邏輯相關的所有內容

<Label />簡單地呈現一個文本或你需要的任何東西(可能frame.rows[i][idx])

...意味著他們很可能會有一些值/處理程序作為道具傳遞

在你的代碼中,你有這個:


let form = `<form onSubmit=${ (e:any) => {this.handleSubmit(e)} } ><input type="text" value=${e.currentTarget.innerText} className="input-small gf-form-input width-auto"/></form>`

我相信它應該是一個獨立的組件,有自己的狀態和邏輯(例如提交)。事實上,這就是<Input ... />我的例子。如果你把它作為一個單獨的組件 - 以下代碼將起作用(因為它將成為該單獨組件的一部分):


handleSubmit(e) {

  e.preventDefault()        

}

最后,避免做這樣的事情:


e.currentTarget.innerHTML =  form;

重新考慮你的方法,你根本不需要做那樣的事情。


查看完整回答
反對 回復 2022-11-03
?
絕地無雙

TA貢獻1946條經驗 獲得超4個贊

您可以像下面這樣使用它:


1-我假設您有一個如下所示的返回按鈕,因此您可以不使用表單提交事件提交作為回報:


_handleReturn(){

let val = document.getElementById("your input id");

//you can post above text to server if you want

   //Do Somthing

}

<button id="btn_return" onClick={this._handleReturn} />

2-我看不到你在哪里觸發了handleSubmit,但是提交表單會導致刷新,如果你不想的話,你應該使用ajax。


查看完整回答
反對 回復 2022-11-03
  • 3 回答
  • 0 關注
  • 314 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號