我正在尝试将一个函数从父级传递给子级,但我得到“无法读取未定义的属性'getDays'。”
以下是来自父母的片段:
getDays:function(){return this.state.days;},
...
renderComponents:function(){
if (typeof(this.state.days)==='undefined'){
var days = 0;
}else{
days = this.state.days;
}
console.log(days);
if (this.state.showWorkDoneMaintenance){
return <WorkDoneMaintenance
subjects={this.props.subjects}
workdone={this.props.workdone}
getDays={this.getDays}
/>;
}
然后是孩子:
var WorkDoneMaintenance = React.createClass({
...
renderWorkDoneItems:function() {
var items = [];
this.props.workdone.map(function(workdone){
if (TimeUtility.dateIsToday(workdone.createdAt,this.props.getDays())){
items.push(workdone);
}
});
return items.map((workdone) => (
<tr key={workdone._id}>
...
propTypes:{
getDays:React.PropTypes.func,
subjects:React.PropTypes.array,
workdone:React.PropTypes.array
}
});
对于传递的数组(主题和workdone)似乎没有任何问题,但我似乎无法弄清楚函数的问题。
答案 0 :(得分:0)
如果你写:this.props.workdone.map(function(workdone){ ... });
,你将无法在映射函数中使用this
。这是JavaScript中的常见问题,以这种方式创建的函数根本不保留this
。要解决此问题,请改用lambda表示法,这样会保留this
:this.props.workdone.map(workdone => { ... });
有关详细信息,请参阅https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Functions/Arrow_functions