在JSX中添加空格的最佳做法 [英] Best practice when adding whitespace in JSX

查看:325
本文介绍了在JSX中添加空格的最佳做法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我了解(以及为什么)在JSX中添加空格,但是我想知道什么是最佳实践,或者是否有什么真正的区别?

I understand how (and why) to add a whitespace in JSX, but I am wondering what's best practice or if any makes any real difference?

将两个元素都包裹在一个范围内

<div className="top-element-formatting">
  <span>Hello </span>
  <span className="second-word-formatting">World!</span>
</div>

将它们添加到一行

  <div className="top-element-formatting">
    Hello <span className="second-word-formatting">World!</span>
  </div>

使用JS添加空间

<div className="top-element-formatting">
    Hello {" "}
    <span className="second-word-formatting">World!</span>
</div>

推荐答案

由于&nbsp会导致您使用不间断的空格,因此仅应在必要时使用它.在大多数情况下,这会产生意想不到的副作用.

Because &nbsp causes you to have non-breaking spaces, you should only use it where necessary. In most cases, this will have unintended side effects.

React的旧版本(我相信v14之前的所有版本)会在标记中包含换行符时自动插入<span> </span>.

Older versions of React, I believe all those before v14, would automatically insert <span> </span> when you had a newline inside of a tag.

尽管他们不再这样做,但这是在您自己的代码中处理此问题的一种安全方法.除非您具有专门针对span的样式(通常是不好的做法),否则这是最安全的方法.

While they no longer do this, that's a safe way to handle this in your own code. Unless you have styling that specifically targets span (bad practice in general), then this is the safest route.

根据您的示例,您可以将它们放在一行上,因为它很短.在更长的情况下,这可能是您应该这样做的方式:

Per your example, you can put them on a single line together as it's pretty short. In longer-line scenarios, this is how you should probably do it:

  <div className="top-element-formatting">
    Hello <span className="second-word-formatting">World!</span>
    <span> </span>
    So much more text in this box that it really needs to be on another line.
  </div>

此方法对于自动修剪文本编辑器也是安全的.

This method is also safe against auto-trimming text editors.

另一种方法是使用{' '},它不会插入随机HTML标记.当样式化,突出显示元素并从DOM中消除混乱时,这可能会更加有用.如果您不需要向后兼容React v14或更早的版本,则应该使用该方法.

The other method is using {' '} which doesn't insert random HTML tags. This could be more useful when styling, highlighting elements, and removes clutter from the DOM. If you don't need backwards compatibility with React v14 or earlier, this should be your preferred method.

  <div className="top-element-formatting">
    Hello <span className="second-word-formatting">World!</span>
    {' '}
    So much more text in this box that it really needs to be on another line.
  </div>

这篇关于在JSX中添加空格的最佳做法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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