码迷,mamicode.com
首页 > 其他好文 > 详细

关于react的疑惑

时间:2019-07-27 15:47:57      阅读:104      评论:0      收藏:0      [点我收藏+]

标签:off   输出   col   tor   ret   const   click   reac   set   

直接上代码

<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吗????

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

 

关于react的疑惑

标签:off   输出   col   tor   ret   const   click   reac   set   

原文地址:https://www.cnblogs.com/WildSky/p/11255296.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!