是否有可能在没有渲染的情况下深入遍历React Children?

Mue*_*ers 8 javascript reactjs

有没有办法bar<Wrapper/>'静态'下面获取所有属性,例如没有渲染?

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'));
Run Code Online (Sandbox Code Playgroud)

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

Moh*_*ysy 5

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

-

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

必修知识

  • children是放置在jsx打开和关闭标签内的内容,还是直接注入儿童道具中的内容。除了那个children道具undefined

    <div className="wrapper">
      // Children
      <img src="url" />
    </div>
    
    /* OR */
    
    <div classname="wrapper" children={<img src="url" />}>
    
    Run Code Online (Sandbox Code Playgroud)
  • children是不透明的树状的数据结构,表示反应的元素树中,很可能的输出React.createElement,该jsx器具时transpiling。

    {
      $$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' },
        }
      }
    }
    
    Run Code Online (Sandbox Code Playgroud)
  • 创建React元素并不意味着将它们实例化,而是将它们视为React用于呈现这些元素的描述符。换句话说,实例会React在后台自行处理。

穿越儿童

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

<Wrapper>
  <FooTuple />
</Wrapper>
Run Code Online (Sandbox Code Playgroud)

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

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

如您所见,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>;
    );
  }
}
Run Code Online (Sandbox Code Playgroud)

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

结论

没有干净的方法来增加深层嵌套的孩子或从他们那里抓取一些东西(例如您的箱子)。重构您的代码以另一种方式执行此操作。也许在中提供了一个setter函数context来设置任何深层孩子所需的数据。