React之ref相关使用解析

Ref转发是一个可选属性,其允许某些组件接收ref,并将其向下传递(换句话说,转发它给子组件);

const MyBtn=React.forwardRef((props,ref)=>{
    return (
    <button ref={ref}>test</button>
    );
})
复制代码

使用React.forwardRef来获取传递给它的ref,然后转发到button的DOM上,在使用MyBtn的组件就可以获取底层DOM节点button的ref;

第二个参数 ref 只在使用 React.forwardRef 定义组件时存在。常规函数和 class 组件不接收 ref 参数,且 props 中也不存在 ref;Ref 转发不仅限于 DOM 组件,你也可以转发 refs 到 class 组件实例中。

ref的创建场景有如下几种:

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>
    }
}
复制代码
class Test2 extends React.Component {
    node=null;
    componentDidMount(){
        console.log(this.node)
    }
    render(){
        return <div ref={(node)=>this.node=node}>this is test.</div>
    }
}
复制代码
const Test3=()=>{
    const node=React.useRef(null);
    useEffect(()=>{
        console.log(node.current)
    },[]);
    return <div ref={node}>test.</div>
}
复制代码

上面例子中使用到了useRef,它的作用有:可以用来获取dom元素,或者class组件实例;

还有一个hooks可以配合forwardRef来自定义暴露给父组件的实例值–useImperativeHandle;我们知道对于class组件可以通过ref来获取类组件的实例,但是在子组件是函数组件的情况下,我们不能直接通过ref来获取,而是需要useImperativeHandle和forwradRef来搭配使用;

useImperativeHandle接受三个参数:

  • 第一个参数ref:接受forwardRef传递过来的ref
  • 第二个参数createHandle:处理函数,返回值作为暴露给父组件的ref对象
  • 第三给参数deps:依赖项,依赖项改变产生新的ref对象
© 版权声明
THE END
喜欢就支持一下吧
点赞0 分享