create-react-app 中 onClick 的事件处理程序给出 TypeError undefined
Event handler for onClick in create-react-app gives TypeError undefined
我是第一次使用 create-react-app 创建项目。我正在为 UI 使用 react-bootstrap。我有一个简单的 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>
);
})}
}
}
我一直收到错误消息
TypeError: Cannot read property 'handleClick' of undefined
有人可以帮忙吗?
为 map
回调使用箭头函数以保留 this
绑定到您的 class:
this.state.response.map((object) => {
return (
<ListGroup>
<ListGroupItem onClick={ this.handleClick }>{object.name}
</ListGroupItem>
</ListGroup>
);
})
您还应该使您的处理程序成为箭头函数以保留 this
绑定:
handleClick = (e) => {
this.setState({ clicked: true})
}
Array.prototype.map() 使用第二个参数来设置 'this'。参见
我是第一次使用 create-react-app 创建项目。我正在为 UI 使用 react-bootstrap。我有一个简单的 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>
);
})}
}
}
我一直收到错误消息
TypeError: Cannot read property 'handleClick' of undefined
有人可以帮忙吗?
为 map
回调使用箭头函数以保留 this
绑定到您的 class:
this.state.response.map((object) => {
return (
<ListGroup>
<ListGroupItem onClick={ this.handleClick }>{object.name}
</ListGroupItem>
</ListGroup>
);
})
您还应该使您的处理程序成为箭头函数以保留 this
绑定:
handleClick = (e) => {
this.setState({ clicked: true})
}
Array.prototype.map() 使用第二个参数来设置 'this'。参见