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

styled-components继承自定义组件样式不生效,PrimaryButton样式未识别

问题根因

使用styled()包裹自定义React组件时,styled-components会自动向组件注入样式类名className,你当前的DefaultButton没有接收该属性并挂载到内部真实的按钮DOM节点上,扩展的样式类没有绑定对象,因此不生效。

修复代码

修改DefaultButton.tsx,透传className属性:

import * as S from "./styles";

const DefaultButton = ({ children, className }: { children: React.ReactNode; className?: string }) => {
  return <S.Button className={className}>{children}</S.Button>;
};
export default DefaultButton;

(可选优化)如果需要支持所有按钮原生属性,可以直接继承button的HTML属性类型,后续加onClick、disabled等属性或扩展其他样式都不需要再调整组件结构:

import * as S from "./styles";
import type { ButtonHTMLAttributes } from "react";

const DefaultButton = ({ children, ...rest }: ButtonHTMLAttributes<HTMLButtonElement>) => {
  return <S.Button {...rest}>{children}</S.Button>;
};
export default DefaultButton;

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 22:24:03