1. 程式人生 > 實用技巧 >antd hooks --Function components cannot be given refs. Attempts to access this ref will fail. Did you mean to use React.forwardRef()?

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

問題描述:

在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);