猿问

防止在 React 中提交时刷新页面

我正在尝试创建一个可编辑的表格,该表格将在单击特定单元格后将其转换为一个<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() 似乎不起作用。每次更改文本后按回车键,页面都会刷新。在这种情况下如何阻止页面刷新?


饮歌长啸
浏览 278回答 3
3回答

素胚勾勒不出你

我猜你想要实现一些东西,你可以编辑列,修改或放弃更改,然后根据需要更新内容。这个例子是本地状态,但你仍然可以通过获取数据来做到这一点。单击下面的“运行代码片段”以查看工作示例。// main.jsconst { useState } = React;const App = () => {&nbsp; // State&nbsp; const [data, setData] = useState([{ id: 1, name: 'John', editing: false }, { id: 2, name: 'Kevin', editing: false }]);&nbsp; &nbsp;&nbsp; // Functions&nbsp; const onSubmitForm = index => event => {&nbsp; &nbsp; // To prevent form submission&nbsp; &nbsp; event.preventDefault();&nbsp; &nbsp; // To prevent td onClick&nbsp; &nbsp; event.stopPropagation();&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; const newData = [...data];&nbsp; &nbsp; newData[index].name = newData[index].temp;&nbsp; &nbsp; newData[index].editing = false;&nbsp; &nbsp; delete newData[index].temp;&nbsp; &nbsp; setData(newData);&nbsp; }&nbsp;&nbsp;&nbsp; const onClickToggleEditing = index => event => {&nbsp; &nbsp; // To prevent td onClick and button conflicting with each other for toggling back on&nbsp; &nbsp; event.stopPropagation();&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; const newData = [...data];&nbsp; &nbsp; newData[index].editing = !newData[index].editing;&nbsp; &nbsp; newData[index].temp = newData[index].name;&nbsp; &nbsp; setData(newData);&nbsp; }&nbsp;&nbsp;&nbsp; const onInputChange = index => event => {&nbsp; &nbsp; const newData = [...data];&nbsp; &nbsp; newData[index].temp = event.target.value;&nbsp; &nbsp; setData(newData);&nbsp; &nbsp;&nbsp;&nbsp; }&nbsp; &nbsp;&nbsp; // Render&nbsp; // This basically like having its own component&nbsp; const editing = ( data, index, onChange, onSubmit, onCancel) => {&nbsp;&nbsp;&nbsp; &nbsp; const onKeyUp = index => event => {&nbsp; &nbsp; &nbsp; &nbsp;if (event.key === 'Escape') {&nbsp; &nbsp; &nbsp; &nbsp; onCancel(index)(event);&nbsp; &nbsp; &nbsp; &nbsp;}&nbsp; &nbsp; }&nbsp;&nbsp;&nbsp; &nbsp; 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>&nbsp; }&nbsp;&nbsp;&nbsp; return <main>&nbsp; &nbsp; <h1>Table Editing</h1>&nbsp; &nbsp; <p><small>Click to edit cell for <b>Name</b>.</small></p>&nbsp; &nbsp; <table>&nbsp; &nbsp; &nbsp; <thead>&nbsp; &nbsp; &nbsp; &nbsp; <tr>&nbsp; &nbsp; &nbsp; &nbsp; <th>ID</th>&nbsp; &nbsp; &nbsp; &nbsp; <th>Name</th>&nbsp; &nbsp; &nbsp; &nbsp; </tr>&nbsp; &nbsp; &nbsp; </thead>&nbsp; &nbsp; &nbsp; &nbsp; {data && data.length > 0 && <tbody>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;{data.map((i, k) => <tr key={`row-${k}`}>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <td>{i.id}</td>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <td className="editable" onClick={onClickToggleEditing(k)}>{i.editing ? editing(i, k, onInputChange, onSubmitForm, onClickToggleEditing) : i.name}</td>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; </tr>)}&nbsp; &nbsp; &nbsp; </tbody>}&nbsp; &nbsp; </table>&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; <hr />&nbsp; &nbsp; <p><b>Data Manipulation:</b></p>&nbsp; &nbsp; <pre><code>{JSON.stringify(data, null, '\t')}</code></pre>&nbsp; &nbsp;&nbsp;&nbsp; </main>}ReactDOM.render(<App />, document.querySelector('#root'));body {&nbsp; padding: 0;&nbsp; margin: 0;&nbsp; font-family: Arial,sans-serif;}main {&nbsp; padding: 0 20px;}h1 {&nbsp; font-size: 18px;}table {&nbsp; width: 100%;&nbsp; border-spacing: 0;}table tr td,table tr th {&nbsp; border: 1px solid #efefef;&nbsp; height: 30px;&nbsp; line-height: 30px;&nbsp; text-align: left;&nbsp; padding: 6px;}table tr th:first-child {&nbsp; width: 100px;}.editable:hover {&nbsp; background: #efefef;&nbsp; cursor: pointer;}table input {&nbsp; height: 30px;&nbsp; line-height: 30px;&nbsp; font-size: 14px;&nbsp; padding: 0 6px;&nbsp; margin-right: 6px;}table button {&nbsp; height: 32px;&nbsp; border: none;&nbsp; background: red;&nbsp; color: white;&nbsp; font-size: 14px;&nbsp; padding: 0 10px;&nbsp; border-radius: 4px;&nbsp; margin-right: 5px;&nbsp; cursor: pointer;}table button[type=submit] {&nbsp; height: 32px;&nbsp; border: none;&nbsp; background: green;&nbsp; color: white;&nbsp; font-size: 14px;&nbsp; padding: 0 10px;&nbsp; border-radius: 4px;}hr {&nbsp; border: none;&nbsp; height: 1px;&nbsp; background: #999;&nbsp; margin: 20px 0;}pre {&nbsp; background: #efefef;&nbsp; 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>

30秒到达战场

您的代码中有一些问题。我最好修复它们,而不是尝试解决表单提交的问题。一旦完成,您将不必解决表单的问题 - 根本不会有任何问题。首先,让我们看一下您的可编辑单元格:<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)}&nbsp;&nbsp; &nbsp; style={{padding:'5px'}}&nbsp;&nbsp; &nbsp; key={cellID} id={cellID}>&nbsp; &nbsp; {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) {&nbsp; e.preventDefault()&nbsp; &nbsp; &nbsp; &nbsp;&nbsp;}最后,避免做这样的事情:e.currentTarget.innerHTML =&nbsp; form;重新考虑你的方法,你根本不需要做那样的事情。

绝地无双

您可以像下面这样使用它:1-我假设您有一个如下所示的返回按钮,因此您可以不使用表单提交事件提交作为回报:_handleReturn(){let val = document.getElementById("your input id");//you can post above text to server if you want&nbsp; &nbsp;//Do Somthing}<button id="btn_return" onClick={this._handleReturn} />2-我看不到你在哪里触发了handleSubmit,但是提交表单会导致刷新,如果你不想的话,你应该使用ajax。
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答