React組件refs的使用詳解,reactrefs使用詳解

來源:互聯網
上載者:User

React組件refs的使用詳解,reactrefs使用詳解

ref顧名思義我們知道,其實它就可以被看座是一個組件的參考,也可以說是一個標識。作為組件的屬性,其屬性值可以是一個字串也可以是一個函數。

其實,ref的使用不是必須的。即使是在其適用的情境中也不是非用不可的,因為使用ref實現的功能同樣可以轉化成其他的方法來實現。但是,既然ref有其適用的情境,那也就是說ref自有其優勢。關於這一點和ref的適用情境,官方文檔中是這樣說的:

在從 render 方法中返回 UI 結構之後,你可能想衝出 React 虛擬 DOM 的限制,在 render 返回的組件執行個體上調用某些方法。通常來說,這樣做對於應用中的資料流動是不必要的,因為活躍的資料( Reactive data )流總是確保最新的 props 被傳遞到每一個從 render() 輸出的子級中去。然而,仍然有幾個情境使用這種方式是必須的,或者說是有益的:尋找渲染出的組件的DOM標記(可以認為是DOM的標識ID),在一個大型的非React應用中使用React組件或者是將你現有的代碼轉化成React。

下面我們來看這樣的一個情境(下面的例子經常被用於ref的講解,可見下面描述的情境應該是比較經典的):通過某個事件使<input />元素的值被設為空白字串,然後使該<input />元素獲得焦點。

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>   );  } });

在上面例子中,我們已經實現了點擊按鈕通知input元素將值設為空白字串,但是還沒有實現使input元素獲得焦點。這實現起來有些困難,因為在render()中返回的並不是實際的子組件的組合,僅僅是一個特定時間特定執行個體的描述。這句話感覺挺繞的,其實render返回的是虛擬DOM,並不是真實的DOM。因此我們不需要僅僅著眼於那些從render()中返回的那些組件。

那說到這,對於我們如何?獲得焦點並沒有太大的協助。要想實現獲得焦點這個功能我們需要藉助ref來實現。上面我們提到過ref的值有兩種類型,一種是字串、一種是回呼函數。

ref字串上屬性

React支援一個特殊的屬性,你可以將這個屬性加在任何通過render()返回的組件中。這也就是說對render()返回的組件進行一個標記,可以方便的定位的這個組件執行個體。這就是ref的作用。

ref的形式如下

<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的所有內容,

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.