SUNYIMIN / react-review

react
2 stars 0 forks source link

react中有几种this绑定的方法,有什么优点和缺点 #20

Closed SUNYIMIN closed 4 years ago

SUNYIMIN commented 4 years ago

方式一:bind()

 <button onClick={ this.handleClick.bind(this, '赵四') }>Say Hello</button>
SUNYIMIN commented 4 years ago

react中执行方法为什么要绑定this? 当代码被包括在函数内部执行时,在非严格模式指向全局对象window, 在严格模式指向undefined

SUNYIMIN commented 4 years ago

方法二:箭头函数 <button onClick={ ()=>{ this.handleClick() } }>Say Hello

SUNYIMIN commented 4 years ago

方法三:箭头函数的第二种

 handleClick = (e) => {
        console.log(this.state.message)
    }

    render () {
        return (
            <div>
                <button onClick={ this.handleClick }>Say Hello</button>
            </div>
        )
    }