gpt4 book ai didi

javascript - Reactjs 将方法作为 Prop 传递给 child

转载 作者:可可西里 更新时间:2023-11-01 01:59:39 25 4
gpt4 key购买 nike

有没有办法将当前类的方法作为 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 方法作为 prop 传递给子 SignupSetup,但我得到了错误

未捕获错误:不变违规:replaceState(...):无法在现有状态转换期间更新(例如在 render 内)。渲染方法应该是 props 和 state.react.js:17122 的纯函数

最佳答案

问题出在这里:

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

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

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

关于javascript - Reactjs 将方法作为 Prop 传递给 child ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27172358/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com