Manual Rujukan Bahasa Cina React
/ React Refs
React Refs
React 支持一種非常特殊的屬性 Ref ,你可以用來綁定到 render() 輸出的任何組件上。
這個(gè)特殊的屬性允許你引用 render() 返回的相應(yīng)的支撐實(shí)例( backing instance )。這樣就可以確保在任何時(shí)間總是拿到正確的實(shí)例。
使用方法
綁定一個(gè) ref 屬性到 render 的返回值上:
<input ref="myInput" />
在其它代碼中,通過 this.refs 獲取支撐實(shí)例:
var input = this.refs.myInput; var inputValue = input.value; var inputRect = input.getBoundingClientRect();
完整實(shí)例
你可以通過使用 this 來獲取當(dāng)前 React 組件,或使用 ref 來獲取組件的引用,實(shí)例如下:
實(shí)例
<!DOCTYPE html> <html> <head> <meta charset="UTF-8" /> <title>php中文網(wǎng) React 實(shí)例</title> <script src="http://static.php.cn/assets/react/react-0.14.7/build/react.min.js"></script> <script src="http://static.php.cn/assets/react/react-0.14.7/build/react-dom.min.js"></script> <script src="http://static.php.cn/assets/react/browser.min.js"></script> </head> <body> <div id="example"></div> <script type="text/babel"> var MyComponent = React.createClass({ handleClick: function() { // 使用原生的 DOM API 獲取焦點(diǎn) this.refs.myInput.focus(); }, render: function() { // 當(dāng)組件插入到 DOM 后,ref 屬性添加一個(gè)組件的引用于到 this.refs return ( <div> <input type="text" ref="myInput" /> <input type="button" value="點(diǎn)我輸入框獲取焦點(diǎn)" onClick={this.handleClick} /> </div> ); } }); ReactDOM.render( <MyComponent />, document.getElementById('example') ); </script> </body> </html>
運(yùn)行實(shí)例 ?
點(diǎn)擊 "運(yùn)行實(shí)例" 按鈕查看在線實(shí)例
實(shí)例中,我們獲取了輸入框的支撐實(shí)例的引用,子點(diǎn)擊按鈕后輸入框獲取焦點(diǎn)。
我們也可以使用 getDOMNode()方法獲取DOM元素