react中this指向的问题

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <script src="https://unpkg.com/react@16/umd/react.development.js" crossorigin></script>
    <script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js" crossorigin></script>
    <script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script>
    <div id="test"></div>
    <script type="text/babel">
        class Clock extends React.Component{
            constructor(props){
            super(props)
            this.state={
                date :new Date().toLocaleTimeString()
            }
          this.go = this.go.bind(this)
            }
            go(){
                console.log("go",this);
                this.setState({
                    date:new Date().toLocaleTimeString()
                })
            }
            go1=()=>{
                console.log("go1",this);
                this.setState({
                    date:new Date().toLocaleTimeString()
                })
            }

            render(){
               return (
                   /*
                   箭头函数包裹直接调用:this指向其所在的作用域,即render所在作用域,即实例
                   普通函数包裹 this指向undefined
                   重新绑定this bind每次都会生成一个新的函数,性能差
                   一次性绑定:在构造函数中利用bind一次性绑定
                   最优解:利用箭头函数先包裹住方法go1
                   
                   */
                   <div>
                    <h1>class中this绑定</h1>
                    <h1>{this.state.date}</h1>
                    <button onClick={this.go}>直接调用</button>
                    <button onClick={()=>{this.go()}}>箭头函数包裹直接调用</button>
                    <button onClick={function(){
                        console.log("function",this);
                        this.go
                    }}>普通函数包裹直接调用</button>
                    <button onClick={this.go.bind(this)}>重新绑定</button>
                    <button onClick={this.go}>一次性绑定</button>
                    <button onClick={this.go1}>箭头函数声明</button>
                    </div>
               )
            }
        }
        ReactDOM.render(<Clock/>,document.getElementById("test"))
    </script>
</body>

</html>

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值