ReactJS / JSX中表的内联样式

时间:2018-06-06 17:37:22

标签: css reactjs inline-styles

您好我在React中为表组件添加内联样式时遇到了问题。基本上我正在尝试做的是使表头/单元格的间距相等,所以我添加width: '50%'样式以使其工作。我在控制台中添加了它,但是当我返回将其添加到我的代码中时,它没有。

我尝试将它添加到任何东西只是为了看它是否有效而它没有。有什么我想念的吗?

它看起来像什么:

What it looks like

我希望它看起来像(在向控制台添加宽度样式后): Width 50%

JSX

                    <table className="table table-striped">
                        <thead>
                            <tr styles={{width: '50%'}}>
                                <th styles={{width: '50%'}}>Hello</th>
                                <th styles={{width: '50%'}}>World</th>                                
                            </tr>
                        </thead>
                        <tbody>
                            {(data.length == 0)&&           
                                <tr>
                                    <td>I'm</td>
                                    <td>Sam</td>
                                </tr>
                            }
                        </tbody>
                    </table>

2 个答案:

答案 0 :(得分:2)

如评论中所述

  

将'style'更改为'style' - cidicles

通常,复数样式是人们在将变量传递给另一个组件时使用的惯例,而单数样式是jsx-html标签将内联css的关键字。

其他答案建议直接在css中为html标签添加样式。虽然在不使用类的情况下直接在html标签上添加样式可能会有效但值得注意的是它可能无法很好地扩展。这将需要我们更多的工作来返回并维护/更新原始代码。

答案 1 :(得分:0)

您可以在表格上使用table-layout: fixed; width: 100%来强制相等的列宽:

&#13;
&#13;
table {
  width: 100%;
  table-layout: fixed;
}
table tr th {
  text-align: left;
  background: gray;
  color: white;
}
&#13;
                    <table className="table table-striped">
                        <thead>
                            <tr styles={{width: '50%'}}>
                                <th styles={{width: '50%'}}>Hello</th>
                                <th styles={{width: '50%'}}>World</th>                                
                            </tr>
                        </thead>
                        <tbody        
                                <tr>
                                    <td>I'm</td>
                                    <td>Sam</td>
                                </tr>
                        </tbody>
                    </table>
&#13;
&#13;
&#13;

您的width: 50%最有可能无法工作,因为您的父.table没有设置宽度。您可以尝试将width: 100%添加到表中,然后50%可能会有效。