ref顧名思義咱們知道,其實它就能夠被看座是一個組件的參考,也能夠說是一個標識。做爲組件的屬性,其屬性值能夠是一個字符串也能夠是一個函數。html
其實,ref的使用不是必須的。即便是在其適用的場景中也不是非用不可的,由於使用ref實現的功能一樣能夠轉化成其餘的方法來實現。可是,既然ref有其適用的場景,那也就是說ref自有其優點。關於這一點和ref的適用場景,官方文檔中是這樣說的:react
在從 render 方法中返回 UI 結構以後,你可能想衝出 React 虛擬 DOM 的限制,在 render 返回的組件實例上調用某些方法。一般來講,這樣作對於應用中的數據流動是沒必要要的,由於活躍的數據( Reactive data )流老是確保最新的 props 被傳遞到每個從 render() 輸出的子級中去。然而,仍然有幾個場景使用這種方式是必須的,或者說是有益的:查找渲染出的組件的DOM標記(能夠認爲是DOM的標識ID),在一個大型的非React應用中使用React組件或者是將你現有的代碼轉化成React。git
下面咱們來看這樣的一個場景(下面的例子常常被用於ref的講解,可見下面描述的場景應該是比較經典的):經過某個事件使<input />元素的值被設爲空字符串,而後使該<input />元素得到焦點。github
var App = React.createClass({
getInitialState: function() {
return {userInput: ''};
},
handleChange: function(e) {
this.setState({userInput: e.target.value});
},
clearAndFocusInput: function() {
this.setState({userInput: ''}); // 設置值爲空字符串
//這裏想要實現得到焦點
},
render: function() {
return (
<div>
<input
value={this.state.userInput}
onChange={this.handleChange}
/>
<input type="button"
value="Reset And Focus"
onClick={this.clearAndFocusInput}
/>
</div>
);
}
});web
在上面例子中,咱們已經實現了點擊按鈕通知input元素將值設爲空字符串,可是尚未實現使input元素得到焦點。這實現起來有些困難,由於在render()中返回的並非實際的子組件的組合,僅僅是一個特定時間特定實例的描述。這句話感受挺繞的,其實render返回的是虛擬的DOM,並非真實的DOM。所以咱們不須要僅僅着眼於那些從render()中返回的那些組件。函數
那說到這,對於咱們如何實現得到焦點並無太大的幫助。要想實現得到焦點這個功能咱們須要藉助ref來實現。上面咱們提到過ref的值有兩種類型,一種是字符串、一種是回調函數。this
ref字符串上屬性spa
React支持一個特殊的屬性,你能夠將這個屬性加在任何經過render()返回的組件中。這也就是說對render()返回的組件進行一個標記,能夠方便的定位的這個組件實例。這就是ref的做用。component
ref的形式以下htm
<input ref="myInput" />
要想訪問這個實例,能夠經過this.refs來訪問:
this.refs.myInput
先前版本中,咱們能夠經過React.findDOMNode(this.refs.myInput)來訪問組件的DOM。可是如今,已經放棄了findDOMNode函數了,能夠直接使用this.refs.myInput來進行訪問。
ref回調函數
ref屬性也能夠是一個回調函數而不是一個名字。 這個函數將要在組件被掛載以後當即執行。這個參照的組件將會做爲該函數的參數,這個函數能夠當即使用這個組件參數,固然也能夠將其保存供之後使用。
其形式也比較簡單:
render: function() {
return <TextInput ref={(c) => this._input = c} } />;
},
componentDidMount: function() {
this._input.focus();
},
或者是
render: function() {
return (
<TextInput
ref={function(input) {
if (input != null) {
input.focus();
}
}} />
);
},
這裏須要注意,當這個參照組件被卸載而且這個ref改變的時候,先前的ref的參數值將爲null。這將有效的防止了內存的泄露。因此在上面代碼中會有if判斷:
if(input != null){
input.focus();
}
上面介紹了ref的使用場景和方法,下面咱們就將上面的例子來補充完整,從而實現得到焦點的功能
var App = React.createClass({
getInitialState: function() {
return {userInput: ''};
},
handleChange: function(e) {
this.setState({userInput: e.target.value});
},
clearAndFocusInput: function() {
this.setState({userInput: ''}); // Clear the input
// We wish to focus the <input /> now!
if (this.refs.myTextInput !== null) {
this.refs.myTextInput.focus();
}
},
render: function() {
return (
<div>
<input
value={this.state.userInput}
onChange={this.handleChange}
ref=」myTextInput」
/>
<input
type="button"
value="Reset And Focus"
onClick={this.clearAndFocusInput}
/>
</div>
);
}
});
ReactDOM.render(
<App />,
document.getElementById('content')
);
在這個例子中, render 函數返回一個 <input /> 實例的描述。可是真正的實例經過 this.refs. myTextInput獲取。只要 render 返回的某個子組件帶有 ref="myTextInput" ,this.refs. myTextInput就會獲取到正確的實例。
上面就是ref的全部內容,更多關於ref的介紹能夠參考Ref to Components。
對於ref咱們就介紹到這,但願本文對你們有所幫助。