【问题标题】:How to pass nested styling to a component in React如何将嵌套样式传递给 React 中的组件
【发布时间】:2017-12-02 01:57:23
【问题描述】:

我正在使用this 卡片组件,我想在它之上构建。更具体地说,我想内联更改标题的背景颜色。按照我的想法,它看起来像这样:

<Card title='Produção e reembolso' style={{
  ant-card-head: {
    backgroundColor: '#232323'
  }
}} >
  <div> R$ {productionAmount} </div>
</Card>

这不起作用,因为 React 认为 ant-card-head 是一个属性名称。有没有办法做到这一点,或者我必须使用/创建一个不同的组件?

编辑

渲染后的 HTML 如下所示

<div class="ant-card ant-card-bordered">
  <div class="ant-card-head">
    <h3 class="ant-card-head-title">Produção e reembolso</h3>
  </div>
  <div class="ant-card-body">
    <div><!-- react-text: 150 --> R$ <!-- /react-text --></div>
  </div>
</div>

【问题讨论】:

  • ant-card-head 在这种情况下会做什么?为什么不直接传递 backgroundColor 呢?
  • 嗯,这实际上可以工作,如果我发送带有背景的“bodyStyle”:白色
  • 不行,ant-card-head 有一个 background-color: white 属性,所以我需要覆盖它

标签: css reactjs antd


【解决方案1】:

如果您想拥有一个具有样式的通用对象并从那里获取东西,则必须单独声明并使用。

const AllStyles = {
  "ant-card-head": {
    backgroundColor: '#232323'
  },
  "another-thing": {
    backgroundColor: '#ff00aa'
  }
};
<Card title='Produção e reembolso' style={AllStyles["ant-card-head"]} >
<AnotherElem title='Produção e empréstimo' style={AllStyles["another-thing"]} >

如果你只想为这个元素内联样式,你可以这样做

<Card title='Produção e reembolso' style={{
  backgroundColor: '#232323'
}} >

【讨论】:

  • 问题是,卡片组件渲染了这个“ant-card-head”,所以我无法直接访问它,因此无法将样式放在上面。
  • 你可以尝试通过 CSS 设置样式
  • 嗯,是的,但我不想为 8 种不同的标题颜色创建 8 个不同的类。那是我最后的选择,但我心里有数。不过谢谢
猜你喜欢
  • 1970-01-01
  • 2016-12-24
  • 2019-06-26
  • 1970-01-01
  • 2016-08-31
  • 2016-08-05
  • 2021-12-07
  • 2017-04-21
  • 2020-06-06
相关资源
最近更新 更多