React - 使用单个事件处理程序来设置多个输入的状态?

React - use single event handler to set state for multiple inputs?

我是 React 的新手,想知道是否可以使用单个事件处理程序来设置多个输入的状态。也就是说,我不确定如何从输入到处理程序中获取状态“键”,如果这有意义的话。

import React from 'react';

class User extends React.Component {
  constructor(props) {
    super(props);
    this.inputRef = React.createRef();
    this.state = {
      id: props.id,
      firstName: props.firstName,
      lastName: props.lastName,
      email: props.email,
    };
  }

  // how do I (can I) use this single handler to independently change the state of multiple inputs?
  handleChange(e) {
    this.setState({ this.state.key // wrong!: this.inputRef.current.value });
  }

  render() {
    return (
      <div>
        <input type="text" ref={this.inputRef} id={`first_${this.state.id}`} value={this.state.firstName} onChange={this.handleChange.bind(this)} />
        <input type="text" ref={this.inputRef} id={`last_${this.state.id}`} value={this.state.lastName} onChange={this.handleChange.bind(this)} />
        <input type="email" ref={this.inputRef} id={`email_${this.state.id}`} value={this.state.email} onChange={this.handleChange.bind(this)} />
        // imagine ten more inputs
      </div>
    )
  }
}

您尝试做的与 JS 事件处理更相关。

handleChange(event) {
      const {name, value} = event.target;

      this.setState({
          [name]: value
      });
    }
  • event.target 是触发该事件的元素(按钮、文本区域、 等..)你可以从中获取你想要的任何属性(名称, 类型、值等)。
  • setState 你必须使用类似的 状态的名称为元素的名称属性的名称。对于代码 您提供的片段您可以将名称属性添加到第一个输入 标记 <input name = "firstName" .... /> 等等。
  • 同时具有不同类型的输入组合(例如文本区域和复选框)处理起来比较棘手,您可能需要对其进行一些修改或使用条件,但您现在明白了:)
  • 还有一件事不要在 render() 方法中绑定你的处理程序,因为每个都呈现一个全新的函数 returns 绑定处理程序的正确方法之一是在 constructor()方法。