React 支持一種非常特殊的屬性 Ref 湿硝,你可以用來(lái)綁定到 render() 輸出的任何組件上庵芭。
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')
);```