繁体   English   中英

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

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

我有一个自定义挂钩

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

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

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

是否有可能获得组件的唯一名称? 或此用例的任何其他替代方案?

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;
  };

我是用copilot搞定的...

也许useRef可以帮助处理您的案例https://medium.com/trabe/react-useref-hook-b6c9d39e2022

暂无
暂无

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM