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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM