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

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

问题

export default withTranslation('profile')(SSOLoadBtnNew)

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

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

解决问题

查找文档资料,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

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

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

成功解决!!!

知识点

默认情况下,不能在函数组件上使用 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} />
    );
  }
}

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

具体可以参考详细文档

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值