是否可以在不渲染的情况下深度遍历 React 子项

Is it possible to deep traverse React Children without rendering?

本文关键字:深度 情况下 遍历 React 子项 是否      更新时间:2023-09-26

有没有办法抓取"静态"<Wrapper/>中的所有bar属性,例如不渲染?

import React from 'react';
import ReactDOM from 'react-dom';
class Foo extends React.Component {
  render() {
    return(
      <div>
        <span bar="1" /> // want to collect this 'bar'
        <span bar="2" /> // want to collect this 'bar'
      </div>;
    );
  }
}

class FooTuple extends React.Component {
  render() {
    return(
      <div>
        <Foo />
        <Foo />
      </div>;
    );
  }
}
class Wrapper extends React.Component {
  render() {
    React.Children.forEach(this.props.children, child => {
      console.log(child.props); // can only see <FooTuple/> not <Foo/>
    });
    return(
      <div>
        {this.props.children}
      </div>;
    );
  }
}
ReactDOM.render(
  <Wrapper>
    <FooTuple />
  </Wrapper>, 
document.getElementById('app'));

这是一个天真的尝试的 webpackbin,试图迭代显然不起作用child.children,但如果它有帮助,它就在这里:http://www.webpackbin.com/EySeQ-ihg

TL;DR;不,这是不可能的。

--

我曾经遇到过同样的问题,试图遍历一棵嵌套深度的子树。以下是我的独家新闻:

所需知识

  • children是放置在jsx打开和关闭标签内的内容,或直接注入儿童道具中的东西undefined children

    <div className="wrapper">
      // Children
      <img src="url" />
    </div>
    /* OR */
    <div classname="wrapper" children={<img src="url" />}>
    
  • children是一个不透明的树状数据结构,表示 react 元素的树,但它很可能是jsx在转译时实现的React.createElement输出。

    {
      $$typeof: Symbol(react.element),
      type: 'div',
      key: null,
      ref: null,
      props: {
        className: "wrapper",
        children: {
          $$typeof: Symbol(react.element),
          type: 'img',
          key: null,
          ref: null,
          props: { src: 'url' },
        }
      }
    }
    
  • 创建React元素并不意味着它们被实例化,将它们视为React用来呈现这些元素的描述符。 换句话说,实例由幕后React本身来处理。

穿越子项

让我们以您的示例为例,尝试遍历整棵树。

<Wrapper>
  <FooTuple />
</Wrapper>

这些元素的不透明子对象将是这样的:

{
  $$typeof: Symbol(react.element),
  type: Wrapper,
  key: null,
  ref: null,
  props: {
    children: {
      $$typeof: Symbol(react.element),
      type: FooTuple,
      key: null,
      ref: null,
      props: {},
    }
  }
}

如您所见FooTuple道具是空的,原因您现在应该知道。访问其子元素的唯一方法是使用它的type实例化元素,以便能够调用其 render 方法来获取其底层子元素,如下所示:

class Wrapper extends React.Component {
  render() {
    React.Children.forEach(this.props.children, child => {
      const nestedChildren = new child.type(child.props).render();
      console.log(nestedChildren); // `FooTuple` children
    });
    return(
      <div>
        {this.props.children}
      </div>;
    );
  }
}

这显然根本不是需要考虑的事情。

结论

没有干净的方法来增加深度嵌套的孩子或从他们那里抢东西(就像你的情况一样)。重构代码以不同的方式执行此操作。也许在context中提供一个二传手函数来设置你需要的任何深度子级的数据。