css - 使用 "as"属性时,带样式的组件不继承样式

标签 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 在使用 "as" 属性时不会获得 buttonFont 样式。

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

最佳答案

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

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

关于css - 使用 "as"属性时,带样式的组件不继承样式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57948428/

相关文章:

javascript - Gatsby.js 的 GraphQL 查询回调

css - html5shiv 不适用于 IE7

reactjs - 无法使用 React-Konva 渲染内容

html - react : How to make <td> collapse as column in a <tr> in mobile view

ReactJs:将数据获取代码或副作用移至 componentDidUpdate

javascript - 如何在不重新渲染随机放置的同级组件数组的情况下,根据滚动位置更新样式化组件的样式?

css - 样式组件:父样式比子样式具有更高的优先级

html - 使用 CSS 调整图像大小

javascript - 模拟 CSS 弹出框

css - Bootstrap 中 .row 类的负左右边距