我有一个这样布置的组件:
var Entry = React.createClass({
// executes code on a button press.
onButtonClick: function (event) {
// (do stuff)
},
// generates the entry list with a button and some info.
render: function() {
var entryList= this.props.data.map(function(entry) {
// (convert timestamp into relative time, add some tags etc)
return (
<p> entry.information </p>
<a onClick={onButtonClick} className="btn right" id={entry.link}>
go
</a>
);
});
// returns the html of the component
return (
<div className="entryList">
{entryList}
</div>
);
}
});
我希望能够从render函数的entryList变量中运行onButtonClick函数,但似乎无法弄清楚该怎么做。运行该控制台时,控制台显示未定义onButtonClick。
Uncaught ReferenceError: onButtonClick is not defined
如何“转义”功能?我认为这this.props.data.map(function(items) {});
是使问题复杂化的原因,因为从我这样移动按钮就可以很好地访问它
// returns the html of the component
return (
<div className="entryList">
<a onClick={this.onButtonClick} className="btn right">go</a>
{entryList}
</div>
);
}
});
谢谢你的帮助!
您的代码无法按预期方式运行的原因是,上下文this
在传递给的匿名函数内部发生了变化map
。map
接受一个可选的第二个参数,该参数表示this
回调将使用的值。因此,只需添加this
作为第二个参数即可map
解决您的问题。
var entryList = this.props.data.map(function(entry) {
...
}, this);
使用ES2015的开发人员还可以使用箭头功能自动绑定的正确上下文this
。
var entryList = this.props.data.map(entry => {
...
});
参考:https : //developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Array/map
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句