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

前端 未结 3 1432
旧巷少年郎
旧巷少年郎 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:55

    If you're using Babel, you can use this Babel plugin to automatically set the displayName, so that child.type.displayName will equal the string of whatever you've named the component:

    https://www.npmjs.com/package/babel-plugin-add-react-displayname

    It's easy to install and use, just read the directions and make sure to add the plugin name add-react-displayname to your plugins array in your .babelrc file.

    0 讨论(0)
  • 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 }) => <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"));
    <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>

    0 讨论(0)
  • 2020-12-29 10:02

    Use the es6 spread operator:

            React.Children.forEach(children, child => {
                const childType = { ...child.type }
                console.log('child', childType.displayName)
            })
    
    0 讨论(0)
提交回复
热议问题