首页 > 解决方案 > React,Styled-component:覆盖子组件样式

问题描述

我想覆盖 Button 组件样式,但它不起作用。您能告诉我如何覆盖它,还是应该将所有样式都赋予子按钮组件?

按钮.js

const StyledButton = styled.button`
  color: white;
  background-color: yellow;
`;

const Button = ({text}) => {
  return <StyledButton>{text}</StyledButton>;
};

export default Button;

父.js

import Button from "./Button";

const OverrideButton = styled(Button)`
  && {
    color: blue;
    background-color: green;
  }
`;

const Parent = () => {
  return <OverrideButton text="Parent" />;
};

标签: reactjsstyled-components

解决方案


您的课程已创建但未应用。你需要把它传下去。

const Button = ({text, className}) => {
  return <StyledButton className={className}>{text}</StyledButton>;
};

在这里得到了回答:https ://stackoverflow.com/a/54113434/12959556

示例:https ://stackblitz.com/edit/react-a5mdpo?embed=1&file=index.js


推荐阅读