【问题标题】:Why does React update state onChange but not onSubmit (input)?为什么 React 更新状态 onChange 而不是 onSubmit (input)?
【发布时间】:2020-03-22 19:57:37
【问题描述】:

请看下面的代码:

App.jsx

addTodo = event => {
    this.setState({
      newTodo: event.target.value,
      todos: [...this.state.todos, this.state.newTodo]
    });

    console.log(this.state.todos);
  };

AddTodo.jsx

        <form onSubmit={this.props.preventDefault} className="ui form">
          <div className="field">
            <label>Add a todo here:</label>
            <input
              onChange={this.props.addTodo} // addTodo works for onChange why not onSubmit?
              type="text"
              placeholder="Walk the dog..."></input>
            <button type="submit">Submit</button>
          </div>
        </form>

该函数按预期更新 onChange 的状态,但 onSubmit 没有,这是为什么呢?我怀疑它与它所在的标签有关(输入不是表单)。

【问题讨论】:

  • onSubmit 上必须发生什么?
  • 将输入值添加到状态@AnuragSrivastava

标签: javascript reactjs forms


【解决方案1】:

preventDefault 阻止表单执行其默认操作,即提交表单。 Check out the MDN documentationpreventDefault

您需要编写一个自定义函数来处理您希望表单执行的操作并将onSubmit 设置为等于该函数。在该自定义函数中,您可以使用event.preventDefault 来防止表单最初执行其默认操作。然后,稍后在该函数中,您可以编写所需的任何代码来执行您想要执行的任何操作。

这是来自React docs 的示例:

class NameForm extends React.Component {
  constructor(props) {
    super(props);
    this.state = {value: ''};

    this.handleChange = this.handleChange.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
  }

  handleChange(event) {
    this.setState({value: event.target.value});
  }

  handleSubmit(event) {
    alert('A name was submitted: ' + this.state.value);
    event.preventDefault();
  }

  render() {
    return (
      <form onSubmit={this.handleSubmit}>
        <label>
          Name:
          <input type="text" value={this.state.value} onChange={this.handleChange} />
        </label>
        <input type="submit" value="Submit" />
      </form>
    );
  }
}

另外,查看React docs for uncontrolled components 并了解我上面展示的示例(受控组件方法)和不受控组件方法之间的区别。

【讨论】:

    猜你喜欢
    • 2019-11-05
    • 2020-03-10
    • 1970-01-01
    • 2021-10-05
    • 2021-08-01
    • 2021-12-13
    • 2023-03-21
    • 2021-02-17
    • 1970-01-01
    相关资源
    最近更新 更多