Refs and the DOM
在典型的React數(shù)據流中,props是父級組件與子組件交互的唯一方式吕粹。為了修改一個子組件需要用新的props來渲染种柑。然而,存在一些情況需要--脫離典型數(shù)據流的方式去修改子組件匹耕。子組件可以作為一個React組件或DOM元素來修改聚请。
When to Use Refs
這里有幾種使用refs的情況
- 管理焦點、文本選擇稳其、多媒體播放
- 觸發(fā)指令動畫
- 和第三方DOM庫交互
給DOM元素增加一個ref屬性
React支持一個特殊的屬性驶赏,這個屬性可以添加在任何組件中。ref屬性指向了一個callback function(回調函數(shù))既鞠,這個回調函數(shù)會在組件加載或卸載后立即執(zhí)行
當ref屬性被用于HTML元素時煤傍,ref指向的回調函數(shù)接收當前DOM元素作為參數(shù)。例如嘱蛋,下面的代碼使用ref回調函數(shù)去存儲一個DOM節(jié)點的引用
class CustomTextInput extends React.Component {
constructor(props) {
super(props);
this.focus = this.focus.bind(this);
}
focus() {
// Explicitly focus the text input using the raw DOM API
this.textInput.focus();
}
render() {
// Use the `ref` callback to store a reference to the text input DOM
// element in an instance field (for example, this.textInput).
// 注意:ref中的參數(shù)input指的是<input type="text"...這個dom元素蚯姆,參數(shù)input只是個參數(shù)名五续,可以換其他參數(shù)名
return (
<div>
<input
type="text"
ref={(input) => { this.textInput = input; }} />
<input
type="button"
value="Focus the text input"
onClick={this.focus}
/>
</div>
);
}
}
React會在組件裝載時調用回調函數(shù)以DOM元素作為參數(shù),當被卸載時調用回調函數(shù)并將null作為參數(shù)
在Class組件中添加ref
當ref屬性被用于自定義類組件時龄恋,這個ref回調函數(shù) 接受一個已經加載的組件實例作為參數(shù) 疙驾。
class CustomTextInput extends React.Component {
constructor(props) {
super(props);
this.focus = this.focus.bind(this);
}
focus() {
// Explicitly focus the text input using the raw DOM API
this.textInput.focus();
}
render() {
// Use the `ref` callback to store a reference to the text input DOM
// element in an instance field (for example, this.textInput).
return (
<div>
<input
type="text"
ref={(input) => { this.textInput = input; }} />
</div>
);
}
}
class AutoFocusTextInput extends React.Component {
componentDidMount() {
// 這里的focus方法實際上是CustomTextInput組件實例的focus方法
this.textInput.focus();
}
// 這里的ref中的參數(shù)input指的是已經加載完畢的CustomTextInput組件實例,然后將this.textInput指向該實例
render() {
return (
<CustomTextInput
ref={(input) => { this.textInput = input; }} />
);
}
}
Refs和函數(shù)式組件
- 不能在函數(shù)式組件中使用ref屬性篙挽,因為函數(shù)式組件沒有實例
function MyFunctionalComponent() {
return <input />;
}
class Parent extends React.Component {
render() {
// This will *not* work!
// 由于函數(shù)式組件沒有實例荆萤,因此ref中的參數(shù)input其實不是一個組件實例,因此無法通過這種方式獲得組件實例的引用
return (
<MyFunctionalComponent
ref={(input) => { this.textInput = input; }} />
);
}
}
- 如果引用了DOM元素或者類組件铣卡,也是可以在函數(shù)式組件中使用ref屬性的
function CustomTextInput(props) {
// textInput must be declared here so the ref callback can refer to it
let textInput = null;
function handleClick() {
textInput.focus();
}
// 這里ref中的input參數(shù)指的就是該<input type="text".....元素
return (
<div>
<input
type="text"
ref={(input) => { textInput = input; }} />
<input
type="button"
value="Focus the text input"
onClick={handleClick}
/>
</div>
);
}