如何在 React 中将函数组作为props传递?

IT技术 reactjs
2021-05-03 01:35:20

我仅以这个简单的 React 组件为例。

我想在函数“working”和“group.notWorking”中访问this.setState()。

var myComponent = React.createClass({
  getInitialState: function() {
    return {};
  },

  working: function() {
    this.setState({ test: true });  //this is myComponent
  },

  group: {
    notWorking: function() {
      console.log(this); //this is window
    }
  },

  render: function() {
    return (
        <div>
          <ChildComponent working={this.working} group={this.group}/>
        </div>
    );
  },
});

我的问题是如何传递分组在一个对象中的函数,或者是否有任何最佳实践,以避免将所有函数一个一个地传递给子组件。

1个回答

您需要传递它的绑定版本。

<ChildComponent working={this.working} group={this.group.notWorking.bind(this)}/>

如果你想传递整个组,你需要使它成为一个返回一个对象并绑定它的函数:

group: function() {
    return {
        notWorking: function() {
          console.log(this);
        }.bind(this)
    };
}

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind