【问题标题】:how to get current react component name inside custom react hook?如何在自定义反应钩子中获取当前反应组件名称?
【发布时间】:2020-04-02 23:36:07
【问题描述】:

我有一个自定义钩子

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

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

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

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

【问题讨论】:

  • 有帖子解决了您的问题吗?请提供一些反馈将不胜感激。

标签: javascript reactjs


【解决方案1】:
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;
  };

我用副驾驶得到它...

【讨论】:

  • 您的答案可以通过额外的支持信息得到改进。请edit 添加更多详细信息,例如引用或文档,以便其他人可以确认您的答案是正确的。你可以找到更多关于如何写好答案的信息in the help center
【解决方案2】:

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

【讨论】:

    猜你喜欢
    • 2020-02-06
    • 2021-08-25
    • 1970-01-01
    • 1970-01-01
    • 2020-03-08
    • 2019-06-15
    • 1970-01-01
    • 2020-07-18
    • 1970-01-01
    相关资源
    最近更新 更多