使用“ as”属性时,样式化的组件不会继承样式

时间:2019-09-15 21:51:50

标签: css reactjs styled-components

我将styled-systemstyled components一起使用,并且有这样的基本情况:

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。但是在使用StyledLabel属性时,buttonFont无法获得"as"样式。

请在此处查看实时示例:demo

1 个答案:

答案 0 :(得分:0)

我不确定您的最终目标是什么,但是这两个示例在继承方面起作用。但是,它们可能对您的构图没有帮助:

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);