在典型的 React 數(shù)據(jù)流中, 屬性(props)是父組件與子代交互的唯一方式。要修改子組件,你需要通用新的 props 重新渲染它。但是,某些情況下你需要在典型數(shù)據(jù)流外強制修改子代。要修改的子代可以是 React 組件實例,也可以是 DOM 元素。
何時使用 Refs
下面是幾個適合使用 refs 的情況:
處理焦點、文本選擇或媒體控制。
觸發(fā)強制動畫。
集成第三方 DOM 庫
如果可以通過聲明式實現(xiàn),則盡量避免使用 refs。
例如,不要在 Dialog 組件上直接暴露 open() 和 close() 方法,最好傳遞 isOpen 屬性。
不要過度使用 Refs
為 DOM 元素添加 Ref
class CustomTextInput extends React.Component {
constructor(props) {
super(props);
this.focus = this.focus.bind(this);
}
focus() {
// 直接使用原生 API 使 text 輸入框獲得焦點
this.textInput.focus();
}
render() {
// 使用 `ref` 的回調將 text 輸入框的 DOM 節(jié)點存儲到 React
// 實例上(比如 this.textInput)
return (
<div>
<input
type="text"
ref={(input) => { this.textInput = input; }} />
<input
type="button"
value="Focus the text input"
onClick={this.focus}
/>
</div>
);
}
}
為類組件添加 Ref
class AutoFocusTextInput extends React.Component {
componentDidMount() {
this.textInput.focus();
}
render() {
return (
<CustomTextInput
ref={(input) => { this.textInput = input; }} />
);
}
}
如果覺得文章寫得還行,請點個贊。如果想與我進一步交流,可以關注我的公眾號或者加我的微信。

個人微信

公眾號_前端微說.jpg