在React中处理条件样式的正确方法 [英] Correct way to handle conditional styling in React

查看:107
本文介绍了在React中处理条件样式的正确方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我现在正在做一些React,我想知道是否有一种正确的方式来做条件样式。在教程中,他们使用

I'm doing some React right now and I was wondering if there is a "correct" way to do conditional styling. In the tutorial they use

style={{
  textDecoration: completed ? 'line-through' : 'none'
}}

我不想使用内联样式,所以我想改为使用类来控制条件样式。如何以React的思维方式解决这个问题?或者我应该使用这种内联样式方式?

I prefer not to use inline styling so I want to instead use a class to control conditional styling. How would one approach this in the React way of thinking? Or should I just use this inline styling way?

推荐答案

如果您更喜欢使用类名,请务必使用类name。

If you prefer to use a class name, by all means use a class name.

className={completed ? 'text-strike' : null}

您还可以找到类名包有用。有了它,您的代码将如下所示:

You may also find the classnames package helpful. With it, your code would look like this:

className={classNames({ 'text-strike': completed })}

没有正确的方式来进行条件样式。做任何最适合你的事情。对于我自己,我更喜欢避免内联样式并以上述方式使用类。

There's no "correct" way to do conditional styling. Do whatever works best for you. For myself, I prefer to avoid inline styling and use classes in the manner just described.

这篇关于在React中处理条件样式的正确方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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