Стилизованный компонент не наследует стили при использовании в качестве атрибута

Я использую styled-system с styled 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".

См. Живой пример здесь: демонстрация


person dieTrying    schedule 15.09.2019    source источник


Ответы (1)


Я не уверен, какова ваша конечная цель, но эти два примера сработали с точки зрения наследования. Однако они могут не помочь с вашим планом композиции:

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);
person Ricardinho    schedule 16.09.2019