【发布时间】:2021-11-06 12:11:34
【问题描述】:
我在创建任何新组件时遇到代码重复问题。
如何在每次创建新组件时在所有组件之间传递 className 而无需定义 className 属性?
假设我创建了一个名为 ChildComponent 的新组件,我应该定义 className 并为其添加一个默认值,并且每次创建新组件时我都会重新定义 className。
type ChildComponentProps = {
className?: string;
children: string;
};
export default function ChildComponent({ className, children }: ChildComponentProps): JSX.Element {
return <p className={className ?? ''}>{children}</p>;
}
ChildComponent.defaultProps = {
className: null,
};
所以。有什么方法可以在组件之间传递 className 而不会在每个组件中重复代码?
【问题讨论】:
-
你可以使用useRef,google一下
-
假设您在谈论类型定义,您是否尝试过将
ChildComponentProps抽象为全局类型,然后在需要的地方重用它?
标签: javascript reactjs typescript next.js