【问题标题】:How to compose styled components in emotionjs with React?如何使用 React 在emotionjs 中组合样式组件?
【发布时间】:2019-04-08 19:43:10
【问题描述】:

我想做的是将多个样式化的组件组合成一个。

使用纯 css 这很容易:

<button class="btn large red"></button>

这是我在 React 中的情感尝试:

import styled from "@emotion/styled/macro";

const A = styled.button({
  color: "red"
});

const B = styled.button({
  fontSize: 32
});

// I know how to add single styled component. But how to also add B here?
const C = styled(A)({
  // some additional styles
});

function App() {
  return (
    <div className="App">
      <A>A</A>
      <B>B</B>
      <C>C</C>
    </div>
  );
}

请查看演示:

Demo

【问题讨论】:

    标签: javascript reactjs


    【解决方案1】:

    似乎styled 默认情况下无法组合多个样式组件。

    您可能想查看情感herecss 功能。这允许组合多个定义的 css 样式。尽管这需要更多代码行来额外定义 css 对象。

    使用css,您的示例可能如下所示:

    import styled from "@emotion/styled/macro";
    import { css } from "@emotion/core";
    
    import React from "react";
    import ReactDOM from "react-dom";
    
    import "./styles.css";
    
    const red = css({
      color: "red"
    });
    
    const A = styled.button(red);
    
    const bolt = css({
      fontSize: 32
    });
    
    const B = styled.button(bolt);
    
    const C = styled.button(red, bolt);
    
    function App() {
      return (
        <div className="App">
          <A>A</A>
          <B>B</B>
          <C>C</C>
        </div>
      );
    }
    
    const rootElement = document.getElementById("root");
    ReactDOM.render(<App />, rootElement);
    

    Demo

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-11-01
      • 2019-01-14
      • 2020-09-26
      • 1970-01-01
      • 1970-01-01
      • 2021-03-08
      • 1970-01-01
      • 2023-01-03
      相关资源
      最近更新 更多