[英]What is the best way to get the name of a React component?
I have been struggling about finding a method to get the name of a React component.我一直在努力寻找一种方法来获取 React 组件的名称。 I tried the this.constructor.name
property.我尝试了this.constructor.name
属性。 However learnt that it doesn't work in production mode since Webpack minifies the code.但是了解到它在生产模式下不起作用,因为 Webpack 缩小了代码。 Is there any way I can use without any caveats?有什么方法可以在没有任何警告的情况下使用吗?
It's up on from where you need the name.它从你需要名字的地方开始。 If you can treat the component as a function (with hooks) you could just call Function.name
如果您可以将组件视为 function(带挂钩),您可以调用Function.name
function MyComponent({giveNameToParent}){ const sendInfo(){ giveNameToParent(MyComponent.name); } return ( <div onClick={sendInfo}>Hi there;</div> ); }
I don't know if this can solve your problem, but if you need something more solid, please give more context to your case.我不知道这是否可以解决您的问题,但是如果您需要更可靠的东西,请为您的案例提供更多背景信息。
Source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name来源: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.