ReactJS - React.Children.forEach - Can I get the child component name?

前端 未结 3 1434
旧巷少年郎
旧巷少年郎 2020-12-29 09:42

I have a React (15.5.4) component with many children, some of which are HTML elements and some are other React components.

I\'m using server rendering and need the s

3条回答
  •  执笔经年
    2020-12-29 09:59

    You can set the component's name in the property displayName. If you're using ES6 classes, you can set a static property called displayName into component's class. Then, you'll be able to get the child name with child.type.displayName.

    const FirstChild = ({ name }) => 
  • {name}
  • ; FirstChild.displayName = 'FirstChild'; const SecondChild = ({ name }) =>
  • {name}
  • ; SecondChild.displayName = 'SecondChild'; class ThirdChild extends React.Component { static displayName = 'ThirdChild'; render() { return (
  • {this.props.name}
  • ); } } class Parent extends React.Component { componentDidMount() { React.Children.forEach(this.props.children, child => { console.log('name =', child.type.displayName); }) } render() { return (
      {this.props.children}
    ); } } class App extends React.Component { render() { return ( ); } } ReactDOM.render(, document.getElementById("app"));
    
    
    

提交回复
热议问题