【问题标题】:ReactJS: How to apply classname to two element tags? [closed]ReactJS:如何将类名应用于两个元素标签? [关闭]
【发布时间】:2016-12-17 04:24:52
【问题描述】:

我有以下。但是样式只适用于<th>。我尝试了#test-table td, #test-table th {}#test-table td th {},但没有任何应用。

css:

#test-table td, th {
  color: white;
  background-color: yellow;
  text-align: left;
}

代码:

    <table className="test-table">
      <thead>
        <tr>
          <th>head1</th>
          <th>head2</th>
          <th>head3</th>
        </tr>
      </thead>
      <tbody>
        <tr>
          <td>col1</td>
          <td>col2</td>
          <td>col2</td>
        </tr>
      </tbody>
    </table>

如何将样式应用于&lt;td&gt;&lt;th&gt;? css 选择器尤其是 ReactJS 的正确层次结构通常是什么?例如容器通常是className 吗?任何内部元素都用id 定义?

编辑

如何实现:

Table Image

尝试了以下方法但不起作用:

    <table className="test-table">
      <thead>
        <tr>
          <th colspan="2">List</th>
          <th rowspan="2">Monday</th>
          <th rowspan="2">Tuesday</th>
        </tr>
        <tr>
          <th>Names</th>
          <th>Class 1</th><th>Class 2</th>
          <th>Class 1</th><th>Class 2</th>
        </tr>
      </thead>
      <tbody>
        <tr>
          <td>Kev</td>
          <td>abc</td><td>def</td>
          <td>ghi</td><td>jkl</td>
        </tr>
      </tbody>
    </table>

【问题讨论】:

  • 创建小提琴或sn-p请使用!important
  • 在 CSS 中,类选择器是 .,而不是 # 符号。此外,类的 HTML 属性是 class="",而不是 className=""。 ReactJS 与您发布的代码或问题有什么关系?
  • @TylerH 在反应中是 className 因为class 是 JS 的保留字
  • @JordanS 可能是这样,但用户在他的问题中发布了似乎是 HTML 的内容,即class
  • 但是鉴于标题、描述、代码和标签,我猜这是反应......

标签: javascript html css reactjs


【解决方案1】:

您需要使用.,因为您指的是一个类。看看这个小提琴:http://jsfiddle.net/k7wbzc4j/1/ 创建表格并应用 CSS。

【讨论】:

  • 谢谢!至于选择器的层次结构呢?我应该总是对所有事情都使用 className 吗?
  • 你能详细说明一下吗?
  • 在 ReactJS 中使用 css 进行样式设置时,您总是只使用 className 吗?同样在我接受答案之前,我忘了问,但是你能看看编辑下的原帖吗?我似乎无法达到那张桌子。
  • 你总是使用 className 作为反应组件。你的表不工作的原因是因为属性在反应中是驼峰式的。所以colspan 应该是colSpan。这个小提琴正在按您期望的方式工作:jsfiddle.net/k7wbzc4j/2
  • 非常感谢!而且你总是用,是不是也意味着你只用className,没有id和class?
【解决方案2】:

如果您使用 css 选择器,您可以将 #someId 用于 ids 或 .someClass 用于类,但我不知道用于 className 的 css 选择器。一种选择是使用

.test-table td, .test-table th

<table class="test-table">

在这个fiddle中看到

【讨论】:

  • # 选择一个 ID,他们正在尝试选择他们的班级。
  • @craigmasonnc 它也适用于.test-table td, th {}。你知道哪种方式更值得推荐吗?
  • .test-table td, th 将选择所有具有类 test-table 的 td 和所有 th 与类无关。见jsfiddle.net/aeuhfpgm/3
猜你喜欢
  • 2011-07-25
  • 2013-01-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-11-20
  • 1970-01-01
  • 2022-06-15
相关资源
最近更新 更多