Reactjs将方法作为道具传递给子

时间:2014-11-27 13:56:03

标签: javascript reactjs react-jsx

有没有办法将当前类的方法作为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 {渲染{1}}

3 个答案:

答案 0 :(得分:17)

问题在于:

<Button onclick={this.props.setWizardState(1)}></Button>

首先是拼写错误(onClick,首都 C )。但主要问题是你正在调用setWizardState,而onClick需要一个函数。你需要部分应用它。

onClick={this.props.setWizardState.bind(null, 1)}

答案 1 :(得分:6)

如果您有Babel

之类的编译器,也可以使用es6箭头表示法

<Button onclick={() => this.props.setWizardState(1)}></Button>

答案 2 :(得分:0)

在官方reactjs网站上a link。显然你需要绑定这个函数而不是直接应用。

onClick={this.setWizardState.bind(this, 1)}