简体   繁体   English

在React中使用事件处理程序

[英]Currying event handlers in React

I am trying to write a (curried?) onChange event handler on a Component that will receive a key argument which will let it know which key in the state object to update. 我正在尝试在将接收到key参数的Component上编写一个(curried?) onChange事件处理程序,它将使它知道要更新的状态对象中的哪个键。 The code won't compile, saying 'key' is not defined . 该代码不会编译,并说'key' is not defined

class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      firstName: null,
      lastName: null
    }
    this.handleChange = this.handleChange.bind(this);
  }

  handleChange = (key) = (event) => {
    console.log(key, event);
  }

  render() {
    return (
      <div>

        <form>
          <input onChange={this.handleChange('firstName')} value={this.state.firstName} />
          <input onChange={this.handleChange('lastName')} value={this.state.firstName} />
        </form>

        {JSON.stringify(this.state, null, 4)}
      </div>
    );
  }
}

You have to pass both the event as well as the key on the OnChange handler. 您必须传递event以及OnChange处理程序上的key

Do this 做这个

<input onChange={this.handleChange.bind(this,'firstName')} value={this.state.firstName} />

And the onChange should be 并且onChange应该是

 handleChange = (key, event) => {
    console.log(key, event);
  }

This will allow both the event and key to be passed and the function will work. 这将允许同时传递eventkey ,并且该功能将起作用。

I think that in your code you have just forgotten to put the arrow function after initializing first function name: 我认为在您的代码中,您只是忘了在初始化第一个函数名称之后放下箭头函数:

handleChange = (key) = [!!! HERE - should be an arrow !!!] (event) => {
  console.log(key, event);
}

Try to use this: 尝试使用此:

handleChange = (key) => (event) => {
  console.log(key, event);
}

So this way your first function which has the param key will return another function with param event . 这样,您的第一个具有param key函数将返回另一个带有param event函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM