gpt4 book ai didi

javascript - 如何在箭头函数 HOC 中设置 Component displayName

转载 作者:行者123 更新时间:2023-12-05 07:17:50 24 4
gpt4 key购买 nike

我正在尝试弄清楚如何将显示名称添加到我的 HOC 并从以下代码中删除注释 eslint-disable-next-line react/display-name:

const withMyHOC = () => <P extends MyProps>(WrappedComponent: React.ComponentType<P>):
React.FunctionComponent<P> => {
// eslint-disable-next-line react/display-name
return (props: P): ReactElement => (
<MyComponent>
{/* eslint-disable-next-line react/jsx-props-no-spreading */}
<WrappedComponent {...props} />
</MyComponent>);
};

我找到了以下解决方案:

const withMyHOC = () => <P extends MyProps>(WrappedComponent: React.ComponentType<P>):
React.FunctionComponent<P> => {
const innerHOC = (props: P): ReactElement => (
<MyComponent>
{/* eslint-disable-next-line react/jsx-props-no-spreading */}
<WrappedComponent {...props} />
</MyComponent>);
return innerHOC;
};

但我觉得不太好看。

最佳答案

const decorate = <P extends object>(
Component: React.ComponentType<P>,
displayName?:string
): React.FC<P> => ({
...props
}: P) =>{
const WithName = withStyles({})(Component as React.FC)
WithName.displayName = displayName
return <WithName {...props as P} />
}

然后像这样使用:

(注意!需要在组件之外)

const MyComp = decorate(Compo, "MyComp")

关于javascript - 如何在箭头函数 HOC 中设置 Component displayName,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58630998/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com