React-获取组件内部功能组件的displayName



是否可以获取其中功能组件的名称?

类似于:

function CarWasher(props) {
const handleOnPress = () => {
console.log(this.displayName); // <-- Something like this displayName
}
return ...JSX;
};
CarWasher.displayName = "CarWasher";

您可以引用函数的.name属性。

function CarWasher(props) {
const handleOnPress = () => {
console.log(CarWasher.name);
}
handleOnPress();
};
CarWasher();

如果您担心在引用上述变量时会意外出现拼写错误,请考虑使用TypeScript或至少使用no-undefESLint规则。

此外,带有displayName:

function MemoizedCarWasher(props) {
const handleOnPress = () => {
console.log(MemoizedCarWasher.displayName);
}
handleOnPress();
};
MemoizedCarWasher.displayName = "CarWasher";
MemoizedCarWasher();

最新更新