A Ref forward is an optional property that allows some components to receive a Ref and pass it down (in other words, forward it to child components);
const MyBtn=React.forwardRef((props,ref)=>{
return (
<button ref={ref}>test</button>
);
})
Copy the code
The React. ForwardRef function is used to fetch the ref (s) of the button’s DOM.
The second argument, ref, only exists when the react. forwardRef component is defined. Regular functions and class components do not accept ref arguments, and ref does not exist in props. Ref forwarding is not limited to DOM components; you can also forward refs to class component instances.
A REF can be created in the following scenarios:
class Test1 extends React.Component {
constructor(props){
super(props);
this.node=React.createRef();
}
componentDidMount(){
console.log(this.node)
}
render(){
return <div ref={this.node}>this is test.</div>
}
}
Copy the code
class Test2 extends React.Component {
node=null;
componentDidMount(){
console.log(this.node)
}
render(){
return <div ref={(node)=>this.node=node}>this is test.</div>
}
}
Copy the code
const Test3=()=>{
const node=React.useRef(null);
useEffect(()=>{
console.log(node.current)
},[]);
return <div ref={node}>test.</div>
}
Copy the code
In the example above, useRef is used to retrieve DOM elements or class component instances.
There is also an hooks function that works with the forwardRef to customize the instance value exposed to the parent component –useImperativeHandle; We know that for class components, we can obtain the instance of the class component through ref. However, in the case of function components, we cannot obtain the instance directly through REF. Instead, we need useImperativeHandle and forwradRef to use it together.
UseImperativeHandle accepts three parameters:
- Ref: the ref that receives the callback from the forwardRef
- The second argument createHandle: a handler function that returns the value as the ref object exposed to the parent component
- The third parameter is deps: dependency, which changes to produce a new ref object