Refs提供了一个访问在render方法中生成的DOM节点或React元素
Ref通过使用React.createRef() 以及在React elements 上添加ref 属性创建,在构建组件时,ref通常被赋值给instance属性,以便在整个组件中引用它们。
class MyComponent extends React.Component {
constructor(props) {
super(props);
this.myRef = React.createRef();
}
render() {
return <div ref={this.myRef} />;
}
}
当ref在render方法中传递给了一个element后,这个节点的引用在ref的current属性上可访问了
const node = this.myRef.current;
其中,ref的值根据node的类型有些许不同:
class CustomTextInput extends React.Component {
constructor(props) {
super(props);
// create a ref to store the textInput DOM element
this.textInput = React.createRef();
this.focusTextInput = this.focusTextInput.bind(this);
}
focusTextInput() {
// Explicitly focus the text input using the raw DOM API
// Note: we're accessing "current" to get the DOM node
this.textInput.current.focus();
}
render() {
// tell React that we want to associate the ref
// with the `textInput` that we created in the constructor
return (
<div>
<input
type="text"
ref={this.textInput} />
<input
type="button"
value="Focus the text input"
onClick={this.focusTextInput}
/>
</div>
);
}
}
React will assign the current property with the DOM element when the component mounts, and assign it back to null when it unmounts. ref updates happen before componentDidMount or componentDidUpdate lifecycle methods.
当组件挂载的时候,React将把DOM元素赋值给current属性,当组件卸载的时候ref为null,ref 在componentDidMount和componentDidUpdate两个生命周期方法执行时发生更新。
如果我们想模拟上面CustomTextInput组件一加载就触发点击事件,可以在父组件中使用ref
class AutoFocusTextInput extends React.Component {
constructor(props) {
super(props);
this.textInput = React.createRef();
this.myRef=React.createRef();
}
componentDidMount() {
this.textInput.current.focusTextInput();
this.myRef.current.scrollIntoView()
}
render() {
return (
<CustomTextInput ref={this.textInput} />
<div ref={this.myRef}></div>
);
}
}
Note that this only works if CustomTextInput is declared as a class:
注意:以上只有在CustomTextInput被申明为一个类的时候才有效。
function MyFunctionComponent() {
return <input />;
}
class Parent extends React.Component {
constructor(props) {
super(props);
this.textInput = React.createRef();
}
render() {
// 不可以这样!!!!
return (
<MyFunctionComponent ref={this.textInput} />
);
}
}
其他解决办法:使用forwardRef或者将函数组件改成类组件,当然你也可以在函数内部使用ref
https://reactjs.org/docs/refs-and-the-dom.html