React Forms:解释 handleChange() 函数

React Forms: Explaining the handleChange() function

我正在关注此 React tutorial,并且我试图了解以下代码段中发生的一切。有人可以解释一下 handleChange() 在做什么以及为什么它很重要吗?

是为了存储输入的信息,让后台可以process/store吗?

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>
    );
  }
}

this.handleChange 由输入元素触发,并触发 this.state.value 属性 的变化,进而改变输入字段的值。这很重要,因为 React 使用状态在 DOM.

中显示信息

您可以随意命名 handleChange 只要它是从输入字段触发的并且值会更新状态即可。

这里有一些补充阅读:https://reactjs.org/docs/forms.html

handleChange 在您输入任何文本以输入 Name 时调用 并且

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

这正在更新您的状态 this.state 值以及输入使用的相同状态值以显示您当前的输入 value={this.state.value}

举个例子假设你输入“Farro”作为输入,每次你输入handleChange将被调用并更新状态值作为“Farro”并且在输入字段中将显示“法罗”。