当涉及到我的过滤器组件中的 this.onItemClick 时,我认为范围有问题。
出现错误“onItemClick 未定义”。
这是过滤器组件的代码。
var Filter = React.createClass({
getDefaultProps() {
return {
filterList: [],
name: ''
};
},
onItemClick(event) {
event.currentTarget.style.backgroundColor = '#f00';
},
render() {
return (
<div className="filterCloud quarter-section">
<h3>{this.props.name}</h3>
<ul>
{this.props.filterList.map(function(listValue) {
return <li onClick={this.onItemClick}>{listValue}</li>;
})}
</ul>
</div>
)
}});
最佳答案
您应该为 .map
设置 this
回调,因为现在 this
指的是全局范围(在浏览器中它是 window
,或者 undefined
如果你使用 strict mode
)
this.props.filterList.map(function(listValue) {
return <li onClick={this.onItemClick}>{listValue}</li>;
}, this);
^^^^^
关于javascript - 这个范围在一个简单的 React 组件中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38242895/