[英]Passing a function down to a component through props - REACT
I'm trying to pass the 'handleItemClick' function from the 'Dropdown' component, down to they 'Team' component, however, I can't get it past the 'List' component. 我试图将“ Dropdown”组件中的“ handleItemClick”功能传递给他们的“ Team”组件,但是,我无法通过“ List”组件。 The strange thing is, is that when I log the props inside the 'List' it says that 'itemClick' is in the 'this.props' object and yet when I set it as a prop on the 'Team' component it says "Cannot read property 'itemClick' of undefined". 奇怪的是,当我在“列表”中记录道具时,它说“ itemClick”在“ this.props”对象中,而当我将其设置为“团队”组件中的道具时,它说“无法读取未定义的属性“ itemClick”。
Any help would be much appreciated. 任何帮助将非常感激。
Dropdown Component: 下拉组件:
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>
);
}
});
List Component: 列表组件:
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 was close: Kristofen44接近:
Array.prototype.map()
loses the this
from your parent scope inside it's callback. Array.prototype.map()
在回调中从父范围中丢失了this
。 But the function includes a variable input for accessing this
within it: 但是该函数在其中包含用于访问this
变量的变量输入:
var teams = this.props.teams.map(function(team){
return <Team key={team} team={team} teamChoice={this.props.itemClick} />
}, this);
I'm not sure but I think the error resides in List Component's render function when you map team to generate nodes. 我不确定,但是当您映射团队以生成节点时,我认为错误出在List Component的render函数中。 the map callback function loses the context 'this'. 地图回调函数将丢失上下文“ this”。 I think you have to bind the callback function to 'this' explicitly. 我认为您必须将回调函数明确绑定到“ this”。 Like so : 像这样:
var teams = this.props.teams.map(function(team){
return <Team key={team} team={team} teamChoice={this.props.itemClick} />
}.bind(this)); // <------
BTW, being quite new to react, I don't know if it's good practice to pass an whole object to the attribute 'key' of your Team component... I wonder if it's not better to just pass an id or something like that.. 顺便说一句,由于反应很新,我不知道将整个对象传递给Team组件的属性“键”是否是一种好习惯……我想知道传递一个ID或类似的东西是否更好? ..
Hope it helps 希望能帮助到你
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.