ReactJS/JSX 中表格的内联样式

Inline styles for tables in ReactJS/JSX

您好,我在向 React 中的 table 组件添加内联样式时遇到问题。基本上我想要做的是 table header/cells 等间距划分,所以我添加 width: '50%' 样式来完成这项工作。我在控制台中添加了并且它可以工作,但是当我 return 将它添加到我的代码中时,它没有。

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

长什么样子:

我希望它看起来像什么(向控制台添加宽度样式后):

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>

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

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

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

编辑 正如其他用户提到的,也将 styles 更改为 style

如评论所述

Change 'styles' to 'style' – cidicles

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

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