【问题标题】:How to pass the className prop to all components by default without defining it every time默认情况下如何将className prop传递给所有组件而不每次都定义它
【发布时间】: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


【解决方案1】:

扩展 Julio Alves 在他们的 comment 中所写的内容,您可以创建一个包含以下内容的 types/foo.d.ts 文件:

type CustomComponentType = React.FC<{
  className?: string;
}>;

然后在您的代码中您可以直接引用您的CustomComponentType 而无需导入它:

const ChildComponent: CustomComponentType = ({ className, children }) => (
  <p className={className}>{children}</p>
);

export default ChildComponent;

而且,至少在这种情况下,不需要定义defaultProps。

如果您也遇到其他标准道具的类似问题,那么您可以使用 React 提供的类型(技术上是肯定类型),而不是在声明文件中编写每个属性:

const MyParagraphWrapper: React.FC<React.HTMLProps<HTMLParagraphElement>> = ({
  children,
  ...props
}) => <p {...props}>{children}</p>; // eslint-disable-line react/jsx-props-no-spreading

如果你想概括这一点,你可以传递any/unknown。

type GeneralWrapperComponentType = React.FC<React.HTMLProps<unknown>>;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-06-01
    • 2014-10-02
    • 1970-01-01
    • 1970-01-01
    • 2018-07-09
    • 2020-09-08
    • 2011-04-17
    • 2016-06-01
    相关资源
    最近更新 更多