您好,登錄后才能下訂單哦!
小編給大家分享一下react函數(shù)this相關(guān)問題的示例,相信大部分人都還不怎么了解,因此分享這篇文章給大家參考一下,希望大家閱讀完這篇文章后大有收獲,下面讓我們一起去了解一下吧!
react 函數(shù)this相關(guān)
在使用react的過程中,常常因?yàn)楹瘮?shù)的this問題導(dǎo)致執(zhí)行結(jié)果不如預(yù)期?,F(xiàn)梳理下這塊的問題,先看代碼:
import React from "react"; class MsgList extends React.PureComponent { render() { return ( <ul> {this.props.list.map((item, index) => (<li key={index}>{item}</li>))} </ul> ) } } export default class List extends React.Component { constructor(props) { super(props) this.state = { inputMsg: '', list: [123] } } handleInput = (val) => { this.setState({ inputMsg: val.target.value }) } handleSubmit = () => { const text = this.state.inputMsg if (text) { const msg = [...this.state.list, text] this.setState({ inputMsg: '', list: msg }) } } render() { return ( <p> <MsgList list={this.state.list}/> <input type="text" value={this.state.inputMsg} onChange={this.handleInput}/> <button onClick={this.handleSubmit}>提交</button> </p> ) } }
示例代碼實(shí)現(xiàn)了簡單的元素添加和列表展示功能。
其中函數(shù)綁定和定義的方式如下:
// 綁定 onChange={this.handleInput} // 定義 handleInput = (val) => { this.setState({ inputMsg: val.target.value }) }
定義函數(shù)的方式有很多種,比如:
handleInput(val) { console.log(val.target) console.log(this) this.setState({ inputMsg: val.target.value }) }
此時(shí)val.target為<input>元素,但是this為undefined,此時(shí)調(diào)用this.setState會(huì)報(bào)錯(cuò)。
類的方法默認(rèn)是不會(huì)綁定this的,所以這里丟失了函數(shù)執(zhí)行的上下文。那么如果在綁定時(shí)候加上一對括號(hào):
<input type="text" value={this.state.inputMsg} onChange={this.handleInput()}/> // 函數(shù)定義 handleInput(val) { console.log(val.target) console.log(this) this.setState({ inputMsg: val.target.value }) }
此時(shí)添加括號(hào),雖然綁定了上下文,但這樣會(huì)導(dǎo)致函數(shù)在組件渲染的時(shí)候被觸發(fā),而不是等到渲染完成時(shí)通過點(diǎn)擊觸發(fā),且無法響應(yīng)onChange動(dòng)作。組件在渲染過程中觸發(fā)函數(shù),函數(shù)中調(diào)用setState()會(huì)再次調(diào)用render,導(dǎo)致死循環(huán)。
如果在最開始使用.bind()
為函數(shù)綁定上下文,去掉綁定函數(shù)時(shí)的括號(hào),
constructor(props) { super(props) this.state = { inputMsg: 'hello', list: [123] } this.handleInput = this.handleInput.bind(this) }
這時(shí)功能正常。
而最開始我們定義函數(shù)時(shí)用箭頭函數(shù)綁定了上下文,所以也能實(shí)現(xiàn)想要的功能。
除此之外,還有一種書寫方式也可以正常工作,不過實(shí)際上與最開始的寫法是一樣的。
<input type="text" value={this.state.inputMsg} onChange={(e)=>this.handleInput(e)}/>
使用react的時(shí)候要注意this的指向,類默認(rèn)是不會(huì)為方法綁定this,要么在開始的時(shí)候手動(dòng)綁定this,要么可以使用箭頭函數(shù)自動(dòng)綁定上下文。如果不是希望在組件渲染時(shí)就觸發(fā)的函數(shù),那么綁定函數(shù)時(shí)不能加括號(hào)。
以上是“react函數(shù)this相關(guān)問題的示例”這篇文章的所有內(nèi)容,感謝各位的閱讀!相信大家都有了一定的了解,希望分享的內(nèi)容對大家有所幫助,如果還想學(xué)習(xí)更多知識(shí),歡迎關(guān)注億速云行業(yè)資訊頻道!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。