有没有办法将当前类的方法作为props传递给子类
举个例子;
var SignupModal = React.createClass({
mixins: [CheckMixin],
getInitialState: function(){
return {
'wizardstate': 0
}
},
setWizardState: function(state){
var that = this;
switch (state){
case 0:
that.setState({'wizardstate': 0});
break;
case 1:
that.setState({'wizardstate': 1});
break;
case 2:
that.setState({'wizardstate': 2});
break;
case 3:
that.setState({'wizardstate': 3});
break;
case 4:
that.setState({'wizardstate': 4});
break;
}
},
render: function(){
var temp;
switch (this.state.wizardstate){
case 0:
temp = (<SignupSetup setWizardState={this.setWizardState}/>);
break;
case 1:
temp = (<EmailSetup />);
break;
case 2:
temp = (<PasswordSetup />);
break;
case 3:
temp = (<UsernameSetup />);
break;
case 4:
temp = (<CategoriesSetup />);
break;
}
return (<Modal {...this.props} title="Login" animation={false}>
<div className="modal-body">
<div>
{temp}
</div>
</div>
</Modal>)
var SignupSetup = React.createClass({
render: function(){
return (<Button onClick={this.props.setWizardState(1)}></Button>)
}
});
我想将SignupModal的setWizardState方法传递给子SignupSetup作为prop,但是我得到了错误
Uncaught Error: Invariant Violation: replaceState(...): Cannot update during an existing state transition (such as within
render). Render methods should be a pure function of props and state.react.js:17122
问题在这里:
<Button onclick={this.props.setWizardState(1)}></Button>
首先是拼写错误(onClick
,大写字母C)。但主要的问题是你正在调用setWizardState
,而onClick需要一个函数。你需要部分应用它。
onClick={this.props.setWizardState.bind(null, 1)}
如果您有像Babel这样的编译器,也可以使用es6箭头表示法
<Button onclick={() => this.props.setWizardState(1)}></Button>
这是官方reactjs网站上的a link。显然你需要绑定这个函数而不是直接应用。
onClick={this.setWizardState.bind(this, 1)}