如何在反应中动态添加class?

How to dynamically add class in react?

在简单的井字游戏中,当有人获胜时,突出显示导致获胜的三个方块。

<p data-height="265" data-theme-id="0" data-slug-hash="PQyERJ" data-default-tab="js,result" data-user="akshgods" data-embed-version="2" data-pen-title="Simple tic tac game" class="codepen">See the Pen <a href="https://codepen.io/akshgods/pen/PQyERJ/">Simple tic tac game</a> by ganesh (<a href="https://codepen.io/akshgods">@akshgods</a>) on <a href="https://codepen.io">CodePen</a>.</p>
<script async src="https://static.codepen.io/assets/embed/ei.js"></script>

在这个笔中,如果你赢了,你可以在控制台看到,获胜的索引被记录下来。有人可以更新代码并解释一下吗?

编辑 - 2019 年 1 月:

您也可以使用 classnames 包来做到这一点。该包可以在 here 中找到并像这样使用:

classNames('foo', { bar: true }); -> The result classes will be 'foo bar'.
classNames('foo', { bar: false }); -> The result class will be just 'foo'.

因为没看懂你的问题,所以我会回答你写在标题上的问题。

为了在 React 中动态添加 class 和元素,您可以使用 ES2015 中的 Template Strings 功能。

它应该是这样的:

<div className={`main-class ${this.state.isSelected ? 'selected':''}`}></div>

然后一旦状态改变,选择的class将被添加。