首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用"as“属性时,样式化组件不继承样式

使用"as“属性时,样式化组件不继承样式
EN

Stack Overflow用户
提问于 2019-09-16 05:51:50
回答 1查看 431关注 0票数 0

我在styled components中使用styled-system,有一个基本案例,如下所示:

代码语言:javascript
复制
const buttonFont = {
  fontFamily: "Chilanka"
};

// style a boilerplate for text
const Text = styled.div`
  ${typography}
  ${color}
`;

// button blueprint
const Button = ({ children, ...rest }) => {
  return (
    <Text as="button" {...buttonFont } {...rest}>
      {children}
    </Text>
  );
};

// styled button using button
const StyledButton = styled(Button)`
  color: white;
  background-color: gray;
  padding: 10px 20px;
  border: 2px solid black;
`;

// When using "as" this component does not includes buttonFont styles
const StyledLabel = styled(StyledButton).attrs({
  as: "label"
})``;

我想创建一个StyledLabel,它将继承StyledButton的所有样式,但将标记更改为label。但是当使用"as"属性时,StyledLabel不能获得buttonFont样式。

请在这里查看现场示例:demo

EN

回答 1

Stack Overflow用户

发布于 2019-09-16 15:58:00

我不确定你的最终目标是什么,但这两个例子在继承方面是有效的。但是,它们可能对您的合成计划没有帮助:

代码语言:javascript
复制
import React from "react";
import styled, {css} from "styled-components";
import { typography, color } from "styled-system";
import ReactDOM from "react-dom";

import "./styles.css";

const buttonFont = {
  fontFamily: "Chilanka"
};

const Text = styled.div`
  ${typography}
  ${color}
  margin: 24px;
`;

const StyledButton = styled(Text)`
  color: white;
  background-color: gray;
  padding: 10px 20px;
  border: 2px solid black;
`;

const StyledLabel = styled(StyledButton)`
  color: yellow;
`;

const __Text = styled.div`
  ${typography(buttonFont)}
  ${color}
  margin: 24px;
`;

const __StyledButton = styled(__Text)`
  color: white;
  background-color: gray;
  padding: 10px 20px;
  border: 2px solid black;
`;

const __StyledLabel = styled(__StyledButton)`
  color: yellow;
`;

function App() {
  return (
    <div className="App">
      <StyledButton as="button" {...buttonFont}>styled button</StyledButton>
      <StyledLabel as="label" {...buttonFont}>Does inherit styled font with "as"</StyledLabel>
      <br />
      <br />
      <br />
      <__StyledButton as="button">styled button</__StyledButton>
      <__StyledLabel as="label">Does inherit styled font with "as"</__StyledLabel>
    </div>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/57948428

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档