css - 覆盖样式组件中子样式的最佳方法

标签 css reactjs styled-components

我有一个组件,我想覆盖它的样式。我使用 styled-components 来构建它们。

我的疑问是,如何覆盖子组件的样式。

我想知道更好的方法。

例子

 const Child = styles.div'
      font-size: '10px'
    '
    const Wrapper = styles.div'
      color: red
    '
const DummyComponent = () => (
  <Wrapper>
    <Child>Hello</Child>
  </Wrapper>
)

我想更改填充或边距或子项的任何其他属性。

什么是更好的方法。 使用内联样式或类名。或者在 styled-component 中是否有更好的方法来做到这一点。

使用内联样式

const DummyComponent = ({childStyles}) => (
  <Wrapper>
    <Child style={{...childStyles}}>Hello</Child>
  </Wrapper>
)

使用类名

const DummyComponent = ({childClass}) => (
   <Wrapper>
       <Child className={childClass}>Hello</Child>
    </Wrapper>
)

最佳答案

我建议使用类名来覆盖行为。你只需要你的规则更强大。文本:

const DummyComponent = ({childClass}) => (
   <Wrapper className="div--wrapper">
       <Child className="div--child">Hello</Child>
    </Wrapper>
)
// css
.div--wrapper .div--child{
  // override css go here
}

关于css - 覆盖样式组件中子样式的最佳方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56045585/

相关文章:

jquery - 折叠子菜单时取消悬停菜单

html - 更改 css 图像菜单中的当前不透明度

javascript - 如何在点击时使用初始 useState 值

typescript - 在 Typescript 中使用附加字段 react native 自定义 TextInput

javascript - 样式组件的 "css" Prop 和 Storybook 的 TypeScript 问题

javascript - 垂直下拉 CSS 菜单未按预期运行

javascript - 如何使网站的一部分始终可见/固定在底部?

javascript - 在文本框中禁用空格键 - React - JavaScript

javascript - 如果用户中止连接到服务器(连接时刷新、关闭浏览器等),如何停止执行所有功能(多个异步等)

javascript - 在 React 样式组件上使用 'ref' 不起作用