admin管理员组文章数量:1317906
So i've started with React and ES6 and got stuck with very basics. Really appreciate some help.
handleClick() throws an error:
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>
);
}
}
So i've started with React and ES6 and got stuck with very basics. Really appreciate some help.
handleClick() throws an error:
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>
);
}
}
Share
Improve this question
asked Apr 9, 2015 at 21:27
walkthroughthecodewalkthroughthecode
5194 silver badges18 bronze badges
2 Answers
Reset to default 12{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
.
You either have to explicitly set the context by passing a second argument to .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 ponent method to the ponent. React does this for you automatically in a high-performance way, so you can safely remove this call. See BlueBall
so just like this:
{
menuItems.map(
item => <li className={active ? 'active' : ''}
onClick={this.handleClick} key={item.id}>{item.text}</li>
)}
本文标签: javascriptReact 013 class method undefinedStack Overflow
版权声明:本文标题:javascript - React 0.13 class method undefined - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742030273a2416312.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论