简体   繁体   中英

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...

Maybe useRef can help to deal with your case https://medium.com/trabe/react-useref-hook-b6c9d39e2022

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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