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

查看:31
本文介绍了在 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?

推荐答案

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

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

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

您可能还会发现 classnames 包很有帮助.有了它,您的代码将如下所示:

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.

POSTSCRIPT [06-AUG-2019]

虽然 React 对样式没有偏见,但现在我建议使用 CSS-in-JS 解决方案;即 样式组件情感.如果您是 React 的新手,请坚持使用 CSS 类或内联样式.但是一旦您对 React 感到满意,我建议您采用这些库之一.我在每个项目中都使用它们.

Whilst it remains true that React is unopinionated about styling, these days I would recommend a CSS-in-JS solution; namely styled components or emotion. If you're new to React, stick to CSS classes or inline styles to begin with. But once you're comfortable with React I recommend adopting one of these libraries. I use them in every project.

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

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