[英]React 0.13 class method undefined
So i've started with React and ES6 and got stuck with very basics. 所以我从React和ES6开始,并且陷入了非常基础的困境。 Really appreciate some help.
真的很感激一些帮助。
handleClick() throws an error: handleClick()抛出一个错误:
Uncaught TypeError: Cannot read property 'handleClick' of undefined
code follows 代码如下
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>;
})}
Because your code is in strict mode (modules are always in strict mode), this
is undefined
inside the function you pass to .map
. 因为您的代码处于严格模式(模块始终处于严格模式),
this
在传递给.map
的函数中undefined
。
You either have to explicitly set the context by passing a second argument to .map
: 您必须通过将第二个参数传递给
.map
来显式设置上下文:
{menuItems.map(function(item) {
// ...
}, this)}
Or use an arrow function : 或使用箭头功能 :
{menuItems.map(
item => <li className={active ? 'active' : ''} onClick={this.handleClick.bind(this)} key={item.id}>{item.text}</li>
)}
react.js:18794 Warning: bind():
You are binding a component method to the component. react.js:18794 Warning: bind():
您正在将组件方法绑定到组件。 React does this for you automatically in a high-performance way, so you can safely remove this call. React会以高性能方式自动为您执行此操作,因此您可以安全地删除此调用。 See BlueBall
见BlueBall
so just like this: 就像这样:
{
menuItems.map(
item => <li className={active ? 'active' : ''}
onClick={this.handleClick} key={item.id}>{item.text}</li>
)}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.