簡體   English   中英

如何在 React 中將 ref 向下傳遞多個級別?

[英]How to pass a ref down more than one level in React?

我可以通過forwardRef<Parent />引用傳遞給<Children />

const Children = forwardRef((
  props, ref) => {

  return <div ref={ref}>{props.children}</div>
})

export default function App() {
  const ref = useRef()

  console.log('ref', ref)
  return (
    <Children ref={ref}>I'm a child</Children>
  );
}

但是,當我向<GrandChildren />添加一個級別時,參考返回始終未定義。

const GrandChildren = forwardRef((props, ref) => {

  return <div ref={ref}>{props.children}</div>
})

const Children = forwardRef((
  props, ref) => {

  return <div><GrandChildren ref={ref} /></div>
})

export default function App() {
  const ref = useRef()

  console.log('ref', ref)
  return (
    <Children ref={ref}>I'm a child</Children>
  );
}


我知道我們可以使用 Context 執行此操作並避免道具鑽孔,但對於這個特定示例,我寧願 go 用於道具鑽孔。 任何提示?

您擁有的一種選擇是將 ref 作為道具名稱而不是ref傳遞。 例如:

import { useRef, forwardRef } from "react"

const GrandChildren = forwardRef((props, ref) => {
    return <div ref={ref}>{props.children}</div>
})

const Children = (props) => {
    return (
        <div>
            {props.children}
            <GrandChildren ref={props.grandchildenRef}>
                I'm a grandchild
            </GrandChildren>
        </div>
    )
}

export default function App() {
    const ref = useRef()
    const handleClick = () => {
        console.log("ref", ref)
    }

    return (
        <div onClick={handleClick}>
            <Children grandchildenRef={ref}>I'm a child</Children>
        </div>
    )
}

暫無
暫無

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

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