如何使用情感CSS覆盖React组件的CSS?

时间:2020-04-27 09:40:50

标签: css reactjs emotion

在下面的示例中,如何将background-color:green应用于<Test/>组件而不必直接编辑<Test/>组件?

/** @jsx jsx */
import { css, jsx } from "@emotion/core";
import React from "react";


function Test() {
    return (
        <div
            css={css`
                height: 100px;
                width: 100px;
                background-color: aqua;
            `}
        >
            Text
        </div>
    );
}

function App() {
    return (
        <Test
            css={css`
                height: 400px;
                width: 400px;
                background-color: green;
            `}
        />
    );
}

1 个答案:

答案 0 :(得分:2)

Test必须使用由css-in-js库生成的className属性(在这种情况下为情感):

function Test({ className }) {
  return (
    <div
      className={className}
      css={css`
        height: 100px;
        width: 100px;
        background-color: aqua;
      `}
    >
      Text
    </div>
  );
}

因此:

// Will use the styling defined in `Test` component (default)
<Text/>

// Will use the defined styling and override the default when possible, 
// or add additional styling.
// i.e using background-color will override it
// using background-border will *add* a style
<Text css={...}/>

// Same as above, usually used with 3rd party css.
<Text className="someOtherCss" />