简体   繁体   English

获取 React 组件名称的最佳方法是什么?

[英]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.

相关问题 在React中创建组件参数的最佳方法是什么? - What is the best way to create parameter of the component in React? 从 React-Select 组件获取选定值的最佳方法是什么? - What is the best way to get the selected value from a React-Select component? 在JavaScript中按名称获取cookie的最佳方法是什么? - What is the best way to get a cookie by name in JavaScript? React + Redux - 在表单组件中处理CRUD的最佳方法是什么? - React + Redux - What's the best way to handle CRUD in a form component? 为 React 和 Preact 创建组件库的最佳方法是什么? - What is the best way to create component library for both React and Preact? 向 React 中的每个组件添加相同代码的最佳方法是什么? - What is the best way to add the same code to every component in React? 重构这个 React 组件并保持 DRY 的最佳方法是什么? - What would be the best way to refactor this React component and keep it DRY? 为可重用的 React 组件存储全局变量的最佳方法是什么? - What's the best way to store a global variable for a reusable React component? 将 React 组件注入另一个 React 组件的最佳方法是什么? 还是我应该打扰? - What's the best way to inject a React component into another React component? Or should I bother? 在JS中获取元素标记名称的最佳方法是什么? - What is the best way to get an element's tag name in JS?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM