ReactJS - React.Children.forEach - 我可以获取子组件名称吗?

Ste*_*ast 7 javascript reactjs

我有一个包含许多子节点的React(15.5.4)组件,其中一些是HTML元素,另一些是其他React组件.

我正在使用服务器渲染,并且需要在服务器和客户端上执行相同的操作.客户端将使用React的生产版本.

我需要遍历子项并识别特定类型的React组件.所以我的第一个想法是迭代使用React.Children.forEach()并查找组件名称.

React.Children.forEach(this.props.children, child => {
  console.log('name =', child.name)
})
Run Code Online (Sandbox Code Playgroud)

这似乎child.namechild.displayName不存在.

现在,child.type存在,并且是一个字符串(对于HTML元素)"ul"或者是一个函数(对于React组件).

当它是一个函数时,我可以使用lodash/get这样const type = get(child, 'type.name', '')来获取组件名称.但是,这似乎只在服务器上工作,而不是在客户端生产构建中,它返回一个字符串:"t".看起来开发构建使用我的组件名称作为函数,但生成构建将其重命名为t().所以我不能用child.type.name.

我如何能:

  1. 迭代组件子组件并识别特定类型的组件..?
  2. 哪个适用于开发和生产React构建..?

Jul*_*tta 12

您可以在属性中设置组件的名称displayName.如果您正在使用ES6类,则可以设置一个名为displayNamecomponent的类的静态属性.然后,您将能够获得子名称child.type.displayName.

const FirstChild = ({ name }) => <li>{name}</li>;
FirstChild.displayName = 'FirstChild';

const SecondChild = ({ name }) => <li>{name}</li>;
SecondChild.displayName = 'SecondChild';

class ThirdChild extends React.Component {
  static displayName = 'ThirdChild';
  
  render() {
    return (
      <li>{this.props.name}</li>
    );
  }
  
}

class Parent extends React.Component {
  componentDidMount() {
    React.Children.forEach(this.props.children, child => {
      console.log('name =', child.type.displayName);
    })
  }
  
  render() {
    return (
      <ul>{this.props.children}</ul>
    );
  }
}

class App extends React.Component {
  render() {
    return (
      <Parent>
        <FirstChild name='1st child value' />
        <SecondChild name='2nd child value' />
        <ThirdChild name='3rd child value' />
      </Parent>
    );
  }
}


ReactDOM.render(<App />, document.getElementById("app"));
Run Code Online (Sandbox Code Playgroud)
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="app"></div>
Run Code Online (Sandbox Code Playgroud)

  • 你如何让`static displayName = 'ThirdChild';` 工作?它对我不起作用。 (2认同)