样式化的组件继承不起作用
Posted
技术标签:
【中文标题】样式化的组件继承不起作用【英文标题】:styled components inheritance not working 【发布时间】:2021-12-12 19:14:09 【问题描述】:问题是我有一个 DefaultButton 并且我为它编写了自定义样式的组件。我有一个名为 PrimaryButton 的不同按钮,我想向它写入样式属性。但他没有看到。
这是文件夹结构
DefaultButton.tsx
import * as S from "./styles";
const DefaultButton = ( children : any) =>
return <S.Button>children</S.Button>;
;
export default DefaultButton;
PrimaryButton.tsx
import styled from "styled-components";
import colors from "theme";
import DefaultButton from "./DefaultButton";
const PrimaryButton = styled(DefaultButton)`
background-color: $colors.mainColors.blueOcean;
`;
export default PrimaryButton;
index.tsx 页面
import PrimaryButton from "components";
import type NextPage from "next";
import Head from "next/head";
const Home: NextPage = () =>
return (
<div>
<Head>
<title>Create Next App</title>
<meta name="description" content="Generated by create next app" />
<link rel="icon" href="/favicon.ico" />
</Head>
<h1>hessssllo</h1>
<PrimaryButton>Sıgn in</PrimaryButton>
</div>
);
;
export default Home;
styles.tsx
import styled from "styled-components";
export const Button = styled.button`
font-family: "DM Sans", sans-serif;
cursor: pointer;
display: flex;
justify-content: center;
align-items: center;
`;
用于导入的组件 index.ts
export default as Button from "./Buttons/DefaultButton";
export default as PrimaryButton from "./Buttons/PrimaryButton";
【问题讨论】:
【参考方案1】:您正在尝试将 DefaultButton 设置为 PrimaryButton,它看起来像 <button><button>text</button></button>
,因此您看不到样式按钮。因此,您只需从 styled.ts 中获取样式按钮即可。
PrimaryButton.tsx
import styled from "styled-components";
import Button from "./styles";
const PrimaryButton = styled(Button)`
background-color: blue;
color: white;
`;
export default PrimaryButton;
【讨论】:
以上是关于样式化的组件继承不起作用的主要内容,如果未能解决你的问题,请参考以下文章
使用样式化组件覆盖 antd Button 的样式不起作用?