react报错 TypeError: Cannot read property 'setState' of undefined

import React, { Component } from 'react';


class test extends Component {
    constructor(props) {
        super(props);
        this.state = {
            liked: false
        };
    }
    handleClick(event) {
        this.setState({liked: !this.state.liked});
    }
    render() {
        var text = this.state.liked ? '喜欢' : '不喜欢';
        return (
            <div onClick={this.handleClick}>
                你<b>{text}</b>我。点我切换状态。
            </div>
        );
    }

}


export default test;

渲染是成功的

clipboard.png

但是点击后就会报错

clipboard.png

阅读 6.1k
1 个回答

constructor(props) {
    super(props);
    this.state = {
        liked: false
    };
}

改成

constructor(props) {
    super(props);
    this.state = {
        liked: false
    };
    this.handleClick = this.handleClick.bind(this);
}

方法需要bind this,不然指向不到

推荐问题