关于react的疑惑

直接上代码

<script type="text/babel">
    class Buttons extends React.Component {
        constructor(props) {
            super(props);
            this.state = {button: true};
            this.handle = this.handle.bind(this);
        }
        handle() {
            this.setState((prevState) => ({
                button: !prevState.button
            }));
        }
        render() {
            return(
            <div>
                <button onClick={this.handle}>
                    {this.state.button?'ON': 'OFF'}
                </button>
            </div>)
        }
    }
    ReactDOM.render(
        <Buttons/>,
        document.getElementById('example')
    );
</script>

先说一下为什么函数handleClick要绑定this,

我是这样理解的因为调用handleClick是通过onClick调用的,而onClick是button的属性所以调用函数的时候this就会指向button

可是结果是我在handleClick里面加一个console.log(this),结果是输出undefined,?????????????????????????这是什么操作我也看不懂

还有一点就是为什么在onClick里面使用this.handle,this会指向react组件,????????????????,

按照我的理解是onClick是button的属性,那么在onClick里面使用的话this不应该指向button吗????

希望以后可以知道这些疑惑

猜你喜欢

转载自www.cnblogs.com/WildSky/p/11255296.html
今日推荐