首页 > 解决方案 > 如何在 React 中将 ref 向下传递多个级别?

问题描述

我可以通过以下方式将<Parent />ref传递<Children />forwardRef

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 />但是当我向ref添加一个级别时,返回总是未定义的。

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 来做到这一点并避免道具钻孔,但对于这个特定的例子,我宁愿去道具钻孔。任何提示?

标签: javascriptreactjsrefuse-ref

解决方案


您可以选择的一种选择是将 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>
    )
}

推荐阅读