问题描述:
react组件中的方法获取state中的值时报错:TypeError: Cannot read property ‘state’ of undefined
解决办法:
方法一(在constructor中绑定this到函数):this.funOne = this.funOne.bind(this);
import React , {Component} from 'react';
class Home extends Component {
constructor(props){
super(props);
this.state = {
one: 'one'
}
this.funOne = this.funOne.bind(this); // 主要是这一行绑定this到函数funOne
}
funOne () {
alert(this.state.one)
}
render () {
return (
<div className="Home">
<button onClick={this.funOne}>funOne</button>
</div>
);
}
}
export default Home;
方法二(使用箭头函数):funOne = () => {}
import React , {Component} from 'react';
class Home extends Component {
constructor(props){
super(props);
this.state = {
one: 'one'
}
}
funOne = () => {
alert(this.state.one)
}
render () {
return (
<div className="Home">
<button onClick={this.funOne}>funOne</button>
</div>
);
}
}
export default Home;
方法三(绑定方法的同时绑定this):onClick={this.funOne.bind(this)}
import React , {Component} from 'react';
class Home extends Component {
constructor(props){
super(props);
this.state = {
one: 'one'
}
}
funOne () {
alert(this.state.one)
}
render () {
return (
<div className="Home">
<button onClick={this.funOne.bind(this)}>funOne</button>
</div>
);
}
}
export default Home;
网友评论