代码之家  ›  专栏  ›  技术社区  ›  Pier

如何在react中找到一个功能性子元素的dom元素?

  •  2
  • Pier  · 技术社区  · 6 年前

    显然这是不可能的,但由于我不是反应专家,我想得到确认。

    获取子元素的DOM元素的常用方法是:

    render () {
        const child = React.Children.only(this.props.children);
        const cloned = React.cloneElement(child, {
            ref: this.someRef
        });
        return cloned;
    }
    

    这里的问题是根据 the docs :

    不能对函数组件使用ref属性,因为它们 没有实例

    另一个查找dom元素的选项可以使用 React.findDOMNode() 但是根据来自 this issue 当试图 React.findDOMNode(child) :

    如果要查找子节点之一,则必须添加 首先使用ref(使用react.clonelement),然后使用该ref。

    我们回到前面的问题。

    那么,是否可以找到一个函数组件的DOM元素?

    1 回复  |  直到 6 年前
        1
  •  0
  •   Estus Flask    6 年前

    如中建议的 this question ,对于直接调用无状态组件函数,这可能是少数可接受的情况之一:

    function withRef(SFC) {
      return React.forwardRef((props, ref) => SFC({ref, ...props}));
    }
    
    ...
    
    render () {
      const child = React.Children.only(this.props.children);
      const isFunctional = typeof child === 'function' &&
        (!child.prototype || !child.prototype.isReactComponent);
    
      if (isFunctional) {
        const Child = withRef(child.type);
    
        return <Child {...child.props} ref={this.someRef}/>;
      } else {
        ...
      }
    }
    

    如果功能组件的子组件也不能接受引用,那么这将不起作用。

    在这种形式下,效率很低,因为孩子将被重新渲染。根据目的的不同,可能有更好的方法来实现这一点。一个组件可以被设计成接收一个组件来呈现为一个属性而不是一个子属性。或者,如果特定任务(如设置DOM事件侦听器)需要DOM元素,则可以像 this case .