3 回答

TA貢獻(xiàn)1816條經(jīng)驗(yàn) 獲得超6個(gè)贊
this.changeContent
this.changeContent.bind(this)
onChange
this
window
React.createClass
constructor() { this.changeContent = this.changeContent.bind(this);}
render() { return <input onChange={this.changeContent.bind(this)} />;}
React.refs
React.refs.someref
this.refs.someref
sendContent
this

TA貢獻(xiàn)1804條經(jīng)驗(yàn) 獲得超3個(gè)贊
React.createClass()
React.Component
.
this
React.createClass()
extends React.Component
.
React.createClass()
this
React.Component
this
null
解決這一問題的途徑
將函數(shù)綁定到類構(gòu)造函數(shù)中
。許多人認(rèn)為這是一種最佳實(shí)踐方法,它完全避免觸及JSX,并且不會(huì)為每個(gè)組件重新呈現(xiàn)創(chuàng)建一個(gè)新功能。 class SomeClass extends React.Component { constructor(props) { super(props); this.handleClick = this.handleClick.bind(this); } handleClick() { console.log(this); // the React Component instance } render() { return ( <button onClick={this.handleClick}></button> ); }}
將函數(shù)內(nèi)聯(lián)綁定
。您仍然可以在一些教程/文章/等等中發(fā)現(xiàn)這種方法,因此您必須了解它。它的概念與#1相同,但要注意的是,綁定函數(shù)在每次重呈現(xiàn)時(shí)都會(huì)創(chuàng)建一個(gè)新函數(shù)。 class SomeClass extends React.Component { handleClick() { console.log(this); // the React Component instance } render() { return ( <button onClick={this.handleClick.bind(this)}></button> ); }}
使用胖箭頭函數(shù)
。直到箭頭函數(shù),每個(gè)新函數(shù)都定義了自己的函數(shù)。 this
價(jià)值。但是,箭頭函數(shù)不創(chuàng)建自己的 this
上下文,所以 this
具有來自Reaction組件實(shí)例的原始含義。因此,我們可以: class SomeClass extends React.Component { handleClick() { console.log(this); // the React Component instance } render() { return ( <button onClick={ () => this.handleClick() }></button> ); }}
或 class SomeClass extends React.Component { handleClick = () => { console.log(this); // the React Component instance } render() { return ( <button onClick={this.handleClick}></button> ); }}
使用實(shí)用程序函數(shù)庫自動(dòng)綁定函數(shù)
。有一些實(shí)用程序庫可以自動(dòng)為您完成任務(wù)。以下是一些流行的,僅舉幾個(gè)例子: 自動(dòng)裝配器 是將類的方法綁定到 this
,即使在分離方法時(shí)也是如此。包裹 使用 @autobind
在綁定方法之前 this
指向正確的引用 組件的上下文。 import autobind from 'autobind-decorator';class SomeClass extends React.Component { @autobind handleClick() { console.log(this); // the React Component instance } render() { return ( <button onClick={this.handleClick}></button> ); }}
AutoBindDecorator非常聰明,可以讓我們一次綁定組件類中的所有方法,就像方法1一樣。 類自動(dòng)綁定 是另一個(gè)廣泛用于解決此綁定問題的NPM包。與AutoBindDecorator不同,它不使用裝飾器模式,而是真正使用 只需在構(gòu)造函數(shù)中使用一個(gè)自動(dòng)綁定的函數(shù)。組件的方法以正確引用 this
.import autobind from 'class-autobind';class SomeClass extends React.Component { constructor() { autobind(this); // or if you want to bind only only select functions: // autobind(this, 'handleClick'); } handleClick() { console.log(this); // the React Component instance } render() { return ( <button onClick={this.handleClick}></button> ); }}
PS:其他非常類似的圖書館是 反應(yīng)自綁定 .
建議
其他
你的第一個(gè)傾向可能是在你的應(yīng)用程序中使用參考文獻(xiàn)來“讓事情發(fā)生”。如果是這樣的話,花點(diǎn)時(shí)間更仔細(xì)地考慮一下在組件層次結(jié)構(gòu)中應(yīng)該在哪里擁有狀態(tài)。
state
this.state.inputContent
.
添加回答
舉報(bào)