我想将回调传递给加倍嵌套的组件,并且尽管我能够有效地传递属性,但我不知道如何将回调绑定到正确的组件上才能被触发。我的结构如下所示:
-OutermostComponent
-FirstNestedComponent
-SecondNestedComponent
-DynamicallyGeneratedListItems
单击列表项时应触发一个回调,这是OutermostComponents方法“
onUserInput”,但相反,我得到“未捕获的错误:未定义不是函数”。我怀疑问题出在我如何在第一个内部渲染SecondNestedComponent并将其传递给回调函数。代码看起来像这样:
var OutermostComponent = React.createClass({
onUserInput: //my function,
render: function() {
return (
<div>
//other components
<FirstNestedComponent
onUserInput={this.onUserInput}
/>
</div>
);
}
});
var FirstNestedComponent = React.createClass({
render: function() {
return (
<div>
//other components
<SecondNestedComponent
onUserInput={this.onUserInput}
/>
</div>
);
}
});
var SecondNestedComponent = React.createClass({
render: function() {
var items = [];
this.props.someprop.forEach(function(myprop) {
items.push(<DynamicallyGeneratedListItems myprop={myprop} onUserInput={this.props.onUserInput}/>);}, this);
return (
<ul>
{items}
</ul>
);
}
});
如何正确将回调绑定到适当的嵌套组件?
您正在this.onUserInput
作为的属性传递FirstNestedComponent
。因此,您应该以FirstNestedComponent
身份访问它this.props.onUserInput
。
var FirstNestedComponent = React.createClass({
render: function() {
return (
<div>
<SecondNestedComponent
onUserInput={this.props.onUserInput}
/>
</div>
);
}
});