3 回答

TA貢獻1816條經驗 獲得超6個贊
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貢獻1804條經驗 獲得超3個贊
React.createClass()
React.Component
.
this
React.createClass()
extends React.Component
.
React.createClass()
this
React.Component
this
null
解決這一問題的途徑
將函數綁定到類構造函數中
。許多人認為這是一種最佳實踐方法,它完全避免觸及JSX,并且不會為每個組件重新呈現創建一個新功能。 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> ); }}
將函數內聯綁定
。您仍然可以在一些教程/文章/等等中發現這種方法,因此您必須了解它。它的概念與#1相同,但要注意的是,綁定函數在每次重呈現時都會創建一個新函數。 class SomeClass extends React.Component { handleClick() { console.log(this); // the React Component instance } render() { return ( <button onClick={this.handleClick.bind(this)}></button> ); }}
使用胖箭頭函數
。直到箭頭函數,每個新函數都定義了自己的函數。 this
價值。但是,箭頭函數不創建自己的 this
上下文,所以 this
具有來自Reaction組件實例的原始含義。因此,我們可以: 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> ); }}
使用實用程序函數庫自動綁定函數
。有一些實用程序庫可以自動為您完成任務。以下是一些流行的,僅舉幾個例子: 自動裝配器 是將類的方法綁定到 this
,即使在分離方法時也是如此。包裹 使用 @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一樣。 類自動綁定 是另一個廣泛用于解決此綁定問題的NPM包。與AutoBindDecorator不同,它不使用裝飾器模式,而是真正使用 只需在構造函數中使用一個自動綁定的函數。組件的方法以正確引用 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:其他非常類似的圖書館是 反應自綁定 .
建議
其他
你的第一個傾向可能是在你的應用程序中使用參考文獻來“讓事情發生”。如果是這樣的話,花點時間更仔細地考慮一下在組件層次結構中應該在哪里擁有狀態。
state
this.state.inputContent
.
添加回答
舉報