我正在尝试编写一个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>

结果不会显示在表中,也不会跟踪更改。

最佳答案

通常,在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);

关于javascript - 如何将handleSubmit函数写入setState以获取多种形式,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/56783643/

10-10 00:16