React 中多个输入元素的单个处理程序

Single Handler for multiple input elements in React

我需要从 child 组件更新我的顶级状态。 child 组件有多个 select 列表用于此目的。

在我的 child 组件中:

constructor(props) {
  this.updateNoOfSets = this.updateNoOfSets.bind(this);
  this.updateNoOfRounds = this.updateNoOfRounds.bind(this);
}

updateNoOfSets() {
  this.props.updateNoOfSets(parseInt(this.updatedNoOfSets.value));
}

updateNoOfRounds() {
  this.props.updateNoOfRounds(parseInt(this.updatedNoOfRounds.value));
}

<select
  value={this.props.noOfSets}
  onChange={this.updateNoOfSets}
  ref={(input) => {
    this.updatedNoOfSets = input;
  }}
>
  <option>1</option>
  <option>2</option>
  <option>3</option>
</select>

<select
  value={this.props.noOfRounds}
  onChange={this.updateNoOfRounds}
  ref={(input) => {
    this.updatedNoOfRounds = input;
  }}
>
  <option>1</option>
  <option>2</option>
  <option>3</option>
</select>

在我的 parent:

constructor(props) {
  super(props);
  this.updateNoOfSets = this.updateNoOfSets.bind(this);
  this.updateNoOfRounds = this.updateNoOfRounds.bind(this);
}

updateNoOfSets(noOfSets) {
  this.setState({'noOfSets': noOfSets});
}

updateNoOfRounds(noOfRounds) {
  this.setState({'noOfRounds': noOfRounds});
}

这是有效的,但对我来说似乎很冗长。有没有更短的写法?我的代码示例只有 2 个 select 列表,但我的实际应用程序有更多。

您不需要为每个 select 元素设置多个处理程序。您只需要一个足够智能的处理程序

child:

constructor(props) {
  this.updateValue = this.updateValue.bind(this);
}

updateValue(item, value) {
  this.props.updateValue(item, parseInt(value));
}

<select
  value={this.props.noOfSets}
  onChange={(e) => this.updateValue('noOfSets', e.target.value)}
>
  <option>1</option>
  <option>2</option>
  <option>3</option>
</select>

<select
  value={this.props.noOfRounds}
  onChange={(e) => this.updateValue('noOfRounds', e.target.value)}
>
  <option>1</option>
  <option>2</option>
  <option>3</option>
</select>

Parent:

constructor(props) {
  super(props);
  this.updateValue = this.updateValue.bind(this);
}

updateValue(item, value) {
  this.setState({[item]: value});
}

编辑: 请记住,render 方法中的 binding 函数不是一个好主意,因为每次执行渲染时都会有一个新函数返回,看看

上的这个答案