如何在反应中动态添加类? [英] How to dynamically add class in react?

查看:36
本文介绍了如何在反应中动态添加类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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?

推荐答案

编辑 - 2019 年 1 月:

您也可以使用 classnames 包来做到这一点.可以在此处找到该包,其用法如下:

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.

为了在反应中动态添加类和元素,您可以使用 模板字符串 ES2015 中的功能.

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

它应该是这样的:

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

然后一旦状态改变,就会添加选定的类.

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

这篇关于如何在反应中动态添加类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆