ref是React組件中的一個(gè)特殊特性(attribute),它指向一個(gè)函數(shù),暫叫ref函數(shù)。
當(dāng)組件mount或unmount時(shí)ref函數(shù)會(huì)被調(diào)用,基參數(shù)是原始的DOM對(duì)象或null。當(dāng)ref函數(shù)用在自定義組件上時(shí),其參數(shù)為組件對(duì)象的引用。
因此,我們可以使用ref函數(shù)來(lái)獲取原始DOM對(duì)象。
一個(gè)示例代碼如下:
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; }} /> // 使用ref函數(shù)獲取 input DOM
<input
type="button"
value="Focus the text input"
onClick={this.focus}
/>
</div>
);
}
}
一個(gè)更精練的ref可以如下:
ref={input => this.textInput = input}.
ref函數(shù)將會(huì)在componentDidMount之前被調(diào)用:
class AutoFocusTextInput extends React.Component {
componentDidMount() {
this.textInput.focus();
}
render() {
return (
<CustomTextInput
ref={(input) => { this.textInput = input; }} />
);
}
}
注意:ref函數(shù)無(wú)法應(yīng)用于函數(shù)式組件上。如:
function MyFunctionalComponent() {
return <input />;
}
class Parent extends React.Component {
render() {
// This will *not* work!
return (
<MyFunctionalComponent
ref={(input) => { this.textInput = input; }} /> // 因MyFunctionalComponent是函數(shù)式組件,因此此處ref無(wú)效
);
}
}
但函數(shù)式組件內(nèi)部是可以使用的:
function CustomTextInput(props) {
// textInput must be declared here so the ref callback can refer to it
let textInput = null;
function handleClick() {
textInput.focus();
}
return (
<div>
<input
type="text"
ref={(input) => { textInput = input; }} /> // ref是否有效取決于標(biāo)簽
<input
type="button"
value="Focus the text input"
onClick={handleClick}
/>
</div>
);
}
父級(jí)為了獲取子級(jí)原始DOM元素,可以將一個(gè)set函數(shù)賦值給子級(jí)的props屬性,子級(jí)中再將此props屬性賦值為ref函數(shù)。實(shí)現(xiàn)過(guò)程如下:
function CustomTextInput(props) {
return (
<div>
<input ref={props.inputRef} />
</div>
);
}
class Parent extends React.Component {
render() {
return (
<CustomTextInput
inputRef={el => this.inputElement = el}
/>
);
}
}
上述代碼是一個(gè)兩級(jí)傳遞,實(shí)際上三級(jí)傳遞的實(shí)現(xiàn)也是類(lèi)似,通過(guò)props屬性一層一層往下傳。
React中什么是Uncontrolled Component?
好,這一節(jié)就到這里。Ref函數(shù)是React中一個(gè)非常重要的技巧,希望你掌握了。后續(xù)我將介紹更多React技術(shù)細(xì)節(jié),來(lái)慢慢解答上述問(wèn)題。
想學(xué)計(jì)算機(jī)技術(shù)嗎?需要1對(duì)1專(zhuān)業(yè)級(jí)導(dǎo)師指導(dǎo)嗎?想要團(tuán)隊(duì)陪你一起進(jìn)步嗎?歡迎加我為好友!微信號(hào):iTekka。