簡體   English   中英

ReactJS 無法使用 ref 回調獲取對類組件的 Ref

[英]ReactJS Can not get a Ref to a Class Component using ref callback

我試圖從父組件獲取對子組件(類組件)的引用,我遇到了兩個問題:

Parent component

private childRef: RefObject<any> = React.createRef();

<Child ref={this.childRef} />

  1. ref 回調不會觸發並在我的參考中獲得一個 null {current: null}

  2. React-dev-tools 警告我從功能組件傳遞 ref,但我的子組件是一個類組件..

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

任何人都可以幫忙嗎?

僅供參考 在將我的應用程序從 PReact 遷移到 React 時出現此問題。 在 Preact 中,ref 用於正確傳遞:

家長

 <Child ref={(ref: any) => {
                      if (ref && ref._component) {
                        this.childRef = ref._component._component
                      }
                    }}
</Child>

你必須轉發參考。

const Child = React.forwardRef((props, ref) => (
  <div ref={ref} >
    ....
  </div>
))

ref 不會從功能組件自動傳遞到它的 DOM 元素。 所以你必須手動傳遞它。 更多關於它https://reactjs.org/docs/forwarding-refs.html

將其包裹在 div 中。 嘗試這個:

 Parent component private childRef: RefObject<any> = React.createRef(); <div ref={this.childRef} > <Child /> <div>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM