[英]Passing a function down to a component through props - REACT
我试图将“ Dropdown”组件中的“ handleItemClick”功能传递给他们的“ Team”组件,但是,我无法通过“ List”组件。 奇怪的是,当我在“列表”中记录道具时,它说“ itemClick”在“ this.props”对象中,而当我将其设置为“团队”组件中的道具时,它说“无法读取未定义的属性“ itemClick”。
任何帮助将非常感激。
下拉组件:
var Dropdown = React.createClass({
getInitialState: function(){
return {
display: false
};
},
handleClick: function(e){
this.setState({display: !this.state.display})
},
handleItemClick: function(e){
console.log("Something");
},
render: function(){
return (
<div className="dropdown">
<Button whenClicked={this.handleClick} className="btn-default" title={this.props.data.title} number={this.props.data.teams.length} />
<List teams={this.props.data.teams} display={this.state.display} itemClick={this.handleItemClick}/>
</div>
);
}
});
列表组件:
var List = React.createClass({
render: function(){
console.log(this.props)
var teams = this.props.teams.map(function(team){
return <Team key={team} team={team} teamChoice={this.props.itemClick} />
});
var displayStyle = {
display: this.props.display ? 'block' : 'none'
};
return (
<ul style={displayStyle} className="dropdown-menu">
{teams}
</ul>
);
}
});
Kristofen44接近:
Array.prototype.map()
在回调中从父范围中丢失了this
。 但是该函数在其中包含用于访问this
变量的变量输入:
var teams = this.props.teams.map(function(team){
return <Team key={team} team={team} teamChoice={this.props.itemClick} />
}, this);
我不确定,但是当您映射团队以生成节点时,我认为错误出在List Component的render函数中。 地图回调函数将丢失上下文“ this”。 我认为您必须将回调函数明确绑定到“ this”。 像这样:
var teams = this.props.teams.map(function(team){
return <Team key={team} team={team} teamChoice={this.props.itemClick} />
}.bind(this)); // <------
顺便说一句,由于反应很新,我不知道将整个对象传递给Team组件的属性“键”是否是一种好习惯……我想知道传递一个ID或类似的东西是否更好? ..
希望能帮助到你
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.