React 支持一種非常特殊的屬性 Ref ,你可以用來(lái)綁定到 render() 輸出的任何組件上。
這個(gè)特殊的屬性允許你引用 render() 返回的相應(yīng)的支撐實(shí)例( backing instance )。這樣就可以確保在任何時(shí)間總是拿到正確的實(shí)例。
ref 屬性的值可以是一個(gè)字符串也可以是一個(gè)函數(shù)。
使用方法
綁定一個(gè) ref 屬性到 render 的返回值上:
<input ref="myInput" />
在其它代碼中,通過(guò) this.refs 獲取支撐實(shí)例:
var input = this.refs.myInput;
var inputValue = input.value;
var inputRect = input.getBoundingClientRect();
完整實(shí)例
你可以通過(guò)使用 this 來(lái)獲取當(dāng)前 React 組件,或使用 ref 來(lái)獲取組件的引用,實(shí)例如下:
class MyComponent extends React.Component {
handleClick() {
// 使用原生的 DOM API 獲取焦點(diǎn)
this.refs.myInput.focus();
}
render() {
// 當(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.bind(this)}
/>
</div>
);
}
}
ReactDOM.render(
<MyComponent />,
document.getElementById('example')
);
實(shí)例中,我們獲取了輸入框的支撐實(shí)例的引用,子點(diǎn)擊按鈕后輸入框獲取焦點(diǎn)。
我們也可以使用 getDOMNode()方法獲取DOM元素
更多建議: