React 0.13类方法未定义 [英] React 0.13 class method undefined
本文介绍了React 0.13类方法未定义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
所以我开始使用React和ES6,并且陷入了非常基础的困境。非常感谢一些帮助。
So i've started with React and ES6 and got stuck with very basics. Really appreciate some help.
handleClick()抛出错误:
handleClick() throws an error:
Uncaught TypeError: Cannot read property 'handleClick' of undefined
代码如下
export default class MenuItems extends React.Component {
constructor(props) {
super(props)
this.state = {active: false}
this.handleClick = this.handleClick.bind(this)
}
handleClick() {
this.setState({ active: !this.state.active });
}
render() {
let active = this.state.active
let menuItems = [{text: 'Logo'}, {text: 'promo'}, {text: 'benefits'}, { text: 'form'}]
return (
<ul>
{menuItems.map(function(item) {
return <li className={active ? 'active' : ''} onClick={this.handleClick.bind(this)} key={item.id}>{item.text}</li>;
})}
</ul>
);
}
}
推荐答案
{menuItems.map(function(item) {
return <li className={active ? 'active' : ''} onClick={this.handleClick.bind(this)} key={item.id}>{item.text}</li>;
})}
因为您的代码处于严格模式(模块始终处于严格模式),此
是 undefined
传递给 .map
的函数内部。
Because your code is in strict mode (modules are always in strict mode), this
is undefined
inside the function you pass to .map
.
您必须通过传递<显式设置上下文a href =https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map> .map
:
You either have to explicitly set the context by passing a second argument to .map
:
{menuItems.map(function(item) {
// ...
}, this)}
或者使用箭头功能:
{menuItems.map(
item => <li className={active ? 'active' : ''} onClick={this.handleClick.bind(this)} key={item.id}>{item.text}</li>
)}
这篇关于React 0.13类方法未定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文