简体   繁体   English

如何在自定义反应挂钩中获取当前反应组件名称?

[英]how to get current react component name inside custom react hook?

I have a custom hook我有一个自定义挂钩

function myCustomHook() {
   const currentComponentName = //? 
   return `currentComponentName${customSuffix}`
}

function Sample() {
  const name = myCustomHook()
}

function Component2() {
  const name = myCustomHook()
}

is it possible to get the unique name of a component?是否有可能获得组件的唯一名称? or any other alternative for this use case?或此用例的任何其他替代方案?

const getName = () => {
    const stack = new Error().stack;
    const lines = stack.split("\n");
    const line = lines[3];
    const match = line.match(/at (.*) \(/);
    const name = match[1];
    return name;
  };

I got it using copilot...我是用copilot搞定的...

Maybe useRef can help to deal with your case https://medium.com/trabe/react-useref-hook-b6c9d39e2022也许useRef可以帮助处理您的案例https://medium.com/trabe/react-useref-hook-b6c9d39e2022

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在 React 中找到调用自定义 hook 的组件? - How to find the component calling a custom hook in React? 在另一个组件内部使用时,React 自定义钩子 setValue 未定义 - React custom hook setValue is undefined when used inside another component 如何在生产构建中获取 componentDidCatch 中的反应组件名称? - How to get react component Name inside componentDidCatch in producation build? 如何修复 React 自定义挂钩中的“只能在 function 组件的主体内调用挂钩”错误? - How to fix 'Hooks can only be called inside the body of a function component' error in React custom hook? 如何将 React 组件的自定义钩子与“map”一起使用 - How to use React component's custom hook with “map” 如何在同一个组件中使用自定义反应查询钩子两次? - How to use custom react query hook twice in the same component? React 组件生命周期钩子中`this` 的范围问题 - Scope Issue With `this` Inside React Component Lifecycle Hook 反应中的自定义挂钩不会重新呈现子组件 - custom hook in react does not rerender child component React 使用自定义钩子检测组件外的点击 - React detect click outside a component with custom hook 使用自定义钩子提供的数据测试 React 组件 - Testing React component with data provided by custom hook
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM