react通过外部的箭头函数绑定事件,怎么传参?

代码如下:

handleSwitchColor = (color) => {
    console.log(color);
    const {store} = this.context;
    store.dispatch({
      type: 'CHANGE_COLOR',
      themeColor: 'red'
    })
  };
  render () {
    return (
      <div>
        <button
          style={{ color: this.state.themeColor }}
          onClick={() => this.handleSwitchColor}
        >Red</button>
        <button
          style={{ color: this.state.themeColor }}
          onClick={this.handleSwitchColor}
        >Blue</button>
      </div>
    )
  }

问:

代码中已经为button通过箭头函数绑定上了handleSwitchColor函数,但是通过这种方法的话,怎么给这个函数传参?
this.handleSwitchColor(参数) // 此方式不行
阅读 3.3k
2 个回答

首先不要使用onClick={() => this.handleSwitchColor},这样会每次都会实例化一个高阶函数,使你的页面有性能问题(如果一个页面有上千个这种箭头函数),你应该这样

handleSwitchColor = color => () => {
  console.log(color);
  const { store } = this.context;
  store.dispatch({
    type: "CHANGE_COLOR",
    themeColor: "red"
  });
};
render() {
  let newColor = "yellow";
  return (
    <div>
      <button
        style={{ color: this.state.themeColor }}
        onClick={this.handleSwitchColor(newColor)}
      >
        Red
      </button>
    </div>
  );
}
<button
  style={{ color: this.state.themeColor }}
  onClick={() => {
    this.handleSwitchColor(...)
}}
>Blue</button>

或者

<button
  style={{ color: this.state.themeColor }}
  onClick={this.handleSwitchColor.bind(this, ...)}
>Blue</button>
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题