获取子html名称,javascript – ReactJS – React.Children.forEach – 我可以获取子组件名称吗?...

本文介绍了在React中如何通过设置displayName属性为组件提供名称,以便于在代码中识别和调试。示例展示了在ES6类组件和函数组件中设置displayName的方法,并在Parent组件的componentDidMount生命周期方法中,通过React.Children.forEach遍历并打印子组件的名称。这有助于提升代码可读性和维护性。
摘要由CSDN通过智能技术生成

您可以在属性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"));

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值