React 支持一種非常特殊的屬性?Ref?,你可以用來綁定到 render() 輸出的任何組件上。
反應(yīng)參考文獻(xiàn) 語法
這個特殊的屬性允許你引用 render() 返回的相應(yīng)的支撐實(shí)例( backing instance )。這樣就可以確保在任何時間總是拿到正確的實(shí)例。
反應(yīng)參考文獻(xiàn) 示例
<!DOCTYPE html> <html> <head> <meta charset="UTF-8" /> <title>php.cn React 實(shí)例</title> <script src="https://cdn.bootcss.com/react/15.4.2/react.min.js"></script> <script src="https://cdn.bootcss.com/react/15.4.2/react-dom.min.js"></script> <script src="https://cdn.bootcss.com/babel-standalone/6.22.1/babel.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 屬性添加一個組件的引用于到 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í)例