You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何无需每次定义就为所有组件默认传递className prop

问题描述

我在创建新组件时遇到了代码重复的问题。
如何无需每次创建新组件时都定义className prop,就能在所有组件之间传递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传递,无需在每个组件中重复编写相关代码?


解决方案

方案1:抽离公共Props类型复用

提前定义全局通用的基础组件属性类型,所有自定义组件的Props直接继承该类型即可,无需重复编写className定义:

// 全局公共类型定义,可放在项目公共类型文件如 types/common.ts 中
type BaseComponentProps = {
  className?: string;
  // 还可扩展其他所有组件通用的属性,比如id、内联样式、测试id等
  id?: string;
  style?: React.CSSProperties;
  'data-testid'?: string;
}

后续开发新组件时直接继承该基础类型即可:

import type { BaseComponentProps } from 'types/common';

// 继承基础公共属性后,仅需定义组件特有的属性
type ChildComponentProps = BaseComponentProps & {
  children: string;
};

// 直接通过参数设置默认值,无需单独声明defaultProps
export default function ChildComponent({ className = '', children }: ChildComponentProps): JSX.Element {
  return <p className={className}>{children}</p>;
}

方案2:通过高阶组件封装公共逻辑

如果连参数解构、默认值赋值的逻辑都不想重复编写,可以封装高阶组件统一处理className的注入逻辑:

// 高阶组件定义,可放在公共工具文件中
import type { ComponentType } from 'react';

type WithClassNameProps = {
  className?: string;
}

function withClassName<P extends object>(Component: ComponentType<P & WithClassNameProps>) {
  return function WrappedComponent({ className = '', ...restProps }: P & WithClassNameProps) {
    return <Component className={className} {...restProps as P} />;
  }
}

使用时直接用该高阶组件包裹业务组件即可:

type ChildComponentProps = {
  children: string;
};

function ChildComponent({ className, children }: ChildComponentProps & WithClassNameProps) {
  return <p className={className}>{children}</p>;
}

// 包裹后导出的组件自动支持className属性,无需在组件Props中重复定义
export default withClassName(ChildComponent);

补充说明

React 17及之后的版本更推荐直接使用函数参数默认值替代defaultProps,写法更简洁,和TS类型的适配度也更高,不需要额外编写默认属性的声明代码。


内容的提问来源于stack exchange,提问作者Adel Bassiony

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 05:06:04