[英]Event handler for onClick in create-react-app gives TypeError undefined
I am creating a project using create-react-app for the first time. 我是第一次使用create-react-app创建项目。 I am using react-bootstrap for UI. 我正在为UI使用react-bootstrap。 I have a simple App.js component 我有一个简单的App.js组件
import ListGroup from 'react-bootstrap/lib/ListGroup';
import ListGroupItem from 'react-bootstrap/lib/ListGroupItem';
class App extends Component {
constructor(props) {
super(props);
this.handleClick = this.handleClick.bind(this);
}
handleClick(e) {
this.setState({ clicked: true})
}
render() {
{this.state.response.map(function(object) {
return (
<ListGroup>
<ListGroupItem onClick={ this.handleClick }>{object.name}
</ListGroupItem>
</ListGroup>
);
})}
}
}
I keep getting an error 我不断收到错误消息
TypeError: Cannot read property 'handleClick' of undefined
Could anyone help please? 有人可以帮忙吗?
Use an arrow function for the map
callback to preserve this
binding to your class: 使用箭头功能的map
回调保留this
绑定到类:
this.state.response.map((object) => {
return (
<ListGroup>
<ListGroupItem onClick={ this.handleClick }>{object.name}
</ListGroupItem>
</ListGroup>
);
})
You should also make your handler an arrow function to preserve this
binding: 您还应该使处理程序成为箭头函数以保留this
绑定:
handleClick = (e) => {
this.setState({ clicked: true})
}
Array.prototype.map() takes a second argument to set what 'this'. Array.prototype.map()使用第二个参数来设置“ this”。 See "this" is undefined inside map function Reactjs 看到地图函数Reactjs内部未定义“ this”
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.