首页 > 解决方案 > React forwardRef:你可以向下传递多深的forwardRef?

问题描述

我想知道您可以在嵌套应用程序中将 forwardRef 向下传递多深,以及如何将它传递下去?

像这样的东西:

<Parent>
  <Child>
    ....
  </Child>
</Parent>

    <Child>
      <GrandChild>
          ....      
      </GrandChild>
    </Child>

        <GrandChild>
          <GreatGrandChild>
            ....
          </GreatGrandChild>
        </GrandChild>

            <GreatGrandChild>
              ....
            </GreatGrandChild>

然后在 GreatGrandChild 组件中使用它或将 Parent 中的 ref 和元素向下传递给 GreatGrandChild

标签: reactjsrefreact-forwardref

解决方案


您可以根据需要传递任意深度的 ref,但这似乎效率低下。

一种替代方法是使用上下文 API 在生产者(包含 ref 元素的组件)中设置一个 ref 并在消费者(将使用该 ref 的子级)中使用它


推荐阅读