• React项目——withTranslation (HOC) 高阶组件使用ref遇到的问题


    项目中,父组件想要调用子组件的方法,因此想到了使用 ref,子组件是用 withTranslation 包裹的,因为有翻译的需求。

    问题

    export default withTranslation('profile')(SSOLoadBtnNew)
    
    • 1

    但是,问题来了,出现了报错:

    Warning: Function components cannot be given refs.
    Attempts to access this ref will fail.
    Did you mean to use React.forwardRef()?
    
    • 1
    • 2
    • 3

    解决问题

    查找文档资料,withTranslation (HOC),如何使用 ref

    use ref (>= v10.6.0)

    You can use forwardRefs like:

    const Wrapped = withTranslation('translation', { withRef: true })(MyComponent);
    
    // then pass a ref in your render method like
    const myRef = React.createRef();
    <Wrapped ref={myRef} />;
    
    // use myRef.current to access it
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    因此,在代码中加入 { withRef: true } 可以尝试一波。

    export default withTranslation('profile', { withRef: true })(SSOLoadBtnNew)
    
    • 1

    成功解决!!!

    知识点

    默认情况下,不能在函数组件上使用 ref 属性,因为它们没有实例:

    function MyFunctionComponent() {
      return <input />;
    }
    
    class Parent extends React.Component {
      constructor(props) {
        super(props);
        this.textInput = React.createRef();
      }
      render() {
        // This will *not* work!
        return (
          <MyFunctionComponent ref={this.textInput} />
        );
      }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16

    如果要在函数组件中使用 ref,你可以使用 forwardRef(可与 useImperativeHandle 结合使用),或者可以将该组件转化为 class 组件。

    具体可以参考详细文档

  • 相关阅读:
    Educational Codeforces Round 135 (Rated for Div. 2)
    程序启停分析与进程常用API的使用
    vue开启屏幕录制
    人工智能术语翻译(五)
    Netty实战-实现自己的通讯框架
    vue二次封装-echarts
    使用VScode调试与编写bash脚本
    《JSP》
    搭建Redis哨兵集群
    17条卢松松近期言论汇总
  • 原文地址:https://blog.csdn.net/qq_16525279/article/details/126155561