我想做的是将多个样式化的组件组合为一个。
使用普通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>
);
}
请检查演示:
答案 0 :(得分:1)
默认情况下,styled
似乎无法组合多个样式化的组件。
您可能想看看情绪here的css
功能。这允许组合多个已定义的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);