如何将handleSubmit函数写入setState以获取多种形式

时间:2019-06-27 03:51:46

标签: javascript html reactjs

我正在尝试编写一个handlesubmit函数,该函数可以更改多种形式的状态。我在检索输入值并在handlesubmit函数中使用它时遇到麻烦。另外,当我尝试设置状态时,值将从表中消失。

    handleSubmit = (event) => {
        event.preventDefault();
        let value = this.element.value;
        this.setState({[event.target.id]: value});
    }
   <td>
   {this.state.benchMax}
   </td>
   <td>
   {this.state.ohpMax}
   </td>
<td>
<form id="benchMax" onSubmit={this.handleSubmit}>
<input type="number" ref={el => this.element = el}></input>
<input type="submit" value="Update!"></input>
</form>
</td>
<td>
<form id="ohpMax" onSubmit={this.handleSubmit}>
<input type="number" ref={el => this.element = el}></input>
<input type="submit" value="Update!"></input>
</form>
</td>

结果不会显示在表格中,并且不会跟踪更改。

3 个答案:

答案 0 :(得分:2)

HandleChange函数,

handleChange = event => {
    let value = event.target.value;
    this.setState({[event.target.name]: value})

    event.preventDefault()
    event.stopPropagation()
}

HandlSubmit,

handleSubmit = (event) => {

  //Your code to read values....

  event.preventDefault()
  event.stopPropagation()
}

input内调用handleChange

<input type="number"  name="name1" value={this.state.name1} onChange={this.handleChange} />

答案 1 :(得分:1)

通常,这不是您想要构造表单并在React组件中接收用户输入的方式。

创建表单时,您要遵循以下模式:

user input -> record state -> form submit using state-values

尝试使用此沙箱并查看以下示例:https://codesandbox.io/s/gallant-euler-67w40

import React from "react";
import ReactDOM from "react-dom";

import "./styles.css";

class App extends React.Component {
  state = {
    benchMax: null,
    ohpMax: null,
    submittedBenchMax: null,
    submittedOhpMax: null
  };

  handleSubmit = e => {
    e.preventDefault();
    this.setState({
      submittedBenchMax: this.state.benchMax,
      submittedOhpMax: this.state.ohpMax
    });
  };

  handleOnChange = e => {
    this.setState({
      [e.target.name]: e.target.value
    });
  };

  render() {
    return (
      <div>
        <form id="benchMax" onSubmit={this.handleSubmit}>
          <label>Bench</label>
          <input type="number" name="benchMax" onChange={this.handleOnChange} />
          <input type="submit" value="Update!" />
        </form>
        <form id="ohpMax" onSubmit={this.handleSubmit}>
          <label>Overhead</label>
          <input type="number" name="ohpMax" onChange={this.handleOnChange} />
          <input type="submit" value="Update!" />
        </form>
        <div>
          <h4>Max</h4>
          <p>Bench: {this.state.submittedBenchMax}</p>
          <p>Overhead: {this.state.submittedOhpMax}</p>
        </div>
      </div>
    );
  }
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

答案 2 :(得分:0)

调用setState时,它还会调用render函数,该函数将重置输入字段的值。另外,event.target值引用表单本身,而不是输入字段。尝试在输入字段中使用onChange事件。