【问题标题】:How to override a React component's CSS using emotion CSS?如何使用情感 CSS 覆盖 React 组件的 CSS?
【发布时间】:2020-08-10 19:56:26
【问题描述】:

在下面的示例中,如何将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;
            `}
        />
    );
}

【问题讨论】:

  • 在后台,情感使用className 属性。如果您的Test-组件不接受className,则情感无法改变其样式
  • 抱歉,我不确定我是否理解您的意思?如在function Test( {classname} ) 内提供classname 参数?
  • 是的,请参阅下面丹尼斯的回答以了解实现
  • 另一种采用的模式是将道具传递给子组件

标签: css reactjs emotion


【解决方案1】:

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" />

【讨论】:

  • 这是否意味着可以使用&lt;Test/&gt; 调用Test?还是应该指定classname,例如&lt;Test className="testComponent"/&gt;
猜你喜欢
  • 2021-01-20
  • 1970-01-01
  • 2012-10-14
  • 2020-08-29
  • 2016-01-07
  • 2019-12-25
  • 2021-09-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多