React使用的思考總結
1、事件處理中的this指針問題
在 react 中,用 class 聲明一個組件,調用 class 中的方法時,如果該方法中有 this 且沒有手動綁定 this 指針,則會發生 this 指向 undefined 的問題。
class LoggingButton extends React.Component { constructor(props) { super(props); this.state = {isToggleOn: true} } handleClick() { this.setState(prevState => ({ //報錯,this 指向 undefined,沒有setState方法 isToggleOn: !prevState.isToggleOn })); } render() { return ( <button onClick={this.handleClick}> Click me </button> ); } }
1.1、如何手動綁定方法中的 this 指針
1.1.1、在構造函數中用 bind 綁定 this
constructor(props) { //下面手動綁定了handleClick方法的this指針 this.handleClick = this.handleClick.bind(this); }
1.1.2、在調用時用 bind 綁定 this
class Test extends React.Component { constructor (props) { super(props) this.state = {message: 'Allo!'} } handleClick (name, e) { console.log(this.state.message + name) } render () { return ( <div> //下面在調用時綁定了this指針,并進行了傳參 <button onClick={ this.handleClick.bind(this, '趙四') }>Say Hello</button> </div> ) } }
1.1.3、用箭頭函數聲明函數
class Home extends React.Component { constructor(props) { super(props); this.state = { isToggleOn: true }; } //用箭頭函數聲明可以綁定this handleClick = () => { this.setState(prevState => ({ isToggleOn: !prevState.isToggleOn })); } render() { return ( <button onClick={this.handleClick}> {this.state.isToggleOn ? 'ON' : 'OFF'} </button> ); } }
1.1.4、用箭頭函數調用class中的函數
render() { return ( //用箭頭函數來調用 <button onClick={(e) => {this.handleClick(params, e)} }> {this.state.isToggleOn ? 'ON' : 'OFF'} </button> ); }
使用這個語法有個問題就是每次在組件渲染的時候都會創建一個不同的回調函數,如果這個回調函數作為一個屬性值傳入其它組件,這些組件可能會進行額外的重新渲染。我們通常建議在構造函數中綁定或使用箭頭函數聲明函數的方式來避免這類性能問題。
1.1.5、使用React.createClass
React 15及以下的版本可以React.createClass函數來創建一個組件。你在里面創建的所有函數的this將會自動綁定到組件上。
const App = React.createClass({ handleClick() { console.log('this', this); // this 指向App組件本身 }, render() { return ( <div onClick={this.handleClick}>test</div> ); } });
但是需要注意隨著React 16版本的發布官方已經將改方法從React中移除
1.2、為什么要手動綁定 this
還是有點模糊,給出一些參考鏈接
參考:http://www.fly63.com/article/detial/1013、http://www.rzrgm.cn/dashnowords/p/9343383.html

浙公網安備 33010602011771號