问题描述:

在Antd Form 组件中,当子组件使用Hooks自定义 Function component时,提示以下警告错误。

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

父组件想拿到子组件的 ref,使用 antd 的 Form.create() 包装子组件之后,可以通过包装后的组件的 wrappedComponentRef 拿到子组件的实例。但是因子组件是一个 function component 没有实例,导致不能在子组件上使用 wrappedComponentRef 属性(本质上使用了 ref 属性获得子组件的实例 _class,且 antd 对本来的 ref 属性另外包装了一下,返回的不是子组件的实例 _class)。

即:refs无法获取,这是antd form双向绑定对ref有需要。因为ref和key一样,不是通过prop来传递的,react对其有特殊的处理。

解决方法:

这个可以通过forwardRef包裹函数组件来解决。

官方文档例子:https://zh-hans.reactjs.org/docs/forwarding-refs.html

使用forwardRef转发Ref:


  import React, { forwardRef } from 'react';


function
FundSelect(props, ref) { return ( <YourComponent ref={ref} {...props}> ) } export default forwardRef(FundSelect);