13

有没有办法将当前类的方法作为道具传递给子类

举个例子;

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,但我收到错误消息

Uncaught Error: Invariant Violation: replaceState(...): Cannot update during an existing state transition (such as within使成为). Render methods should be a pure function of props and state.react.js:17122

4

3 回答 3

17

问题在这里:

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

首先是一个错字(onClick, 大写C)。但主要问题是您正在调用setWizardState,并且 onClick 需要一个函数。您需要部分应用它。

onClick={this.props.setWizardState.bind(null, 1)}
于 2014-11-27T14:25:44.687 回答
6

如果你有像Babel这样的编译器,你也可以使用 es6 箭头符号

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

于 2015-04-01T13:56:00.390 回答
0

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

onClick={this.setWizardState.bind(this, 1)}
于 2015-08-16T20:15:59.773 回答