HTML 通常寫法是:
<button onclick="activateLasers()"> 激活按鈕 </button>
React 中寫法為:
<button onClick={activateLasers}> 激活按鈕 </button>
看以上會發現react傳入的是函數名,不加(),如果加了會直接執行。
關於bind
1當你使用 ES6 class 語法來定義一個組件的時候,事件處理器會成為類的一個方法
2你必須謹慎對待 JSX 回調函數中的 this,類的方法默認是不會綁定 this 的。如果你忘記綁定 this.handleClick 並把它傳入 onClick, 當你調用這個函數的時候 this 的值會是 undefined。默認的this指向的是全局,全局中沒有你定義在組建里面的函數。bind后的this指向的是上下文,也就是這個組件,這個組件才有你所需要的方法
3這並不是 React 的特殊行為;它是函數如何在 JavaScript 中運行的一部分。通常情況下,如果你沒有在方法后面添加 () ,例如 onClick={this.handleClick},你應該為這個方法綁定 this。
4在構造函數中bindthis或者在onclick調用的時候bind
this.handleClick = this.handleClick.bind(this);
5還可以如果使用 bind 讓你很煩,這里有兩種方式可以解決。如果你正在使用實驗性的屬性初始化器語法,你可以使用屬性初始化器來正確的綁定回調函數:
class LoggingButton extends React.Component { // 這個語法確保了 `this` 綁定在 handleClick 中 // 這里只是一個測試 handleClick = () => { console.log('this is:', this); } render() { return ( <button onClick={this.handleClick}> Click me </button> ); } }
如果你沒有使用屬性初始化器語法,你可以在回調函數中使用 箭頭函數:
class LoggingButton extends React.Component { handleClick() { console.log('this is:', this); } render() { // 這個語法確保了 `this` 綁定在 handleClick 中 return ( <button onClick={(e) => this.handleClick(e)}> Click me </button> ); } }
這個是一個其他總結
this.x = 9; var module = { x: 81, getX: function() { return this.x; } }; module.getX(); // 返回 81 var retrieveX = module.getX; retrieveX(); // 返回 9, 在這種情況下,"this"指向全局作用域 // 創建一個新函數,將"this"綁定到module對象 // 新手可能會被全局的x變量和module里的屬性x所迷惑 var boundGetX = retrieveX.bind(module); boundGetX(); // 返回 81
即使用bind()方法是為了將函數中的this與當前組件綁定,在該處理函數中的this時刻都指向該組件,避免出現問題。
同時,如今進行this綁定除了bind外還有其他兩種方式
構造函數內綁定
在構造函數 constructor 內綁定this,好處是僅需要綁定一次,避免每次渲染時都要重新綁定,函數在別處復用時也無需再次綁定
import React, {Component} from 'react' class Test extends React.Component { constructor (props) { super(props) this.state = {message: 'Allo!'} this.handleClick = this.handleClick.bind(this) } handleClick (e) { console.log(this.state.message) } render () { return ( <div> <button onClick={ this.handleClick }>Say Hello</button> </div> ) } }
箭頭函數方式
箭頭函數則會捕獲其所在上下文的this值,作為自己的this值,使用箭頭函數就不用擔心函數內的this不是指向組件內部了。可以按下面這種方式使用箭頭函數:
class Test extends React.Component { constructor (props) { super(props) this.state = {message: 'Allo!'} } handleClick (e) { console.log(this.state.message) } render () { return ( <div> <button onClick={ ()=>{ this.handleClick() } }>Say Hello</button> </div> ) } }