How to dynamically add class in react?

陌路散爱 提交于 2019-12-11 09:44:03

问题


In simple tic-tac game,When someone wins, highlight the three squares that caused the win.

<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>

In this pen , you can see in console if you win, the winning indexes are logged. can some one update the code, and explain it?


回答1:


Edit - Jan 2019:

You can also use the classnames package to do that. The package can be found here and is used like this:

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

As I didn't understand your question I will answer the question you wrote on the title.

In order to dynamically add class to and element in react you can use the Template Strings functionality in ES2015.

It should look like this:

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

And then the selected class will be added once the state is changed.



来源:https://stackoverflow.com/questions/48989828/how-to-dynamically-add-class-in-react

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!