您可以在属性displayName中设置组件的名称.如果您正在使用ES6类,则可以将名为displayName的静态属性设置为组件的类.然后,您将能够使用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"));