javascript – 在JSX中添加空格时的最佳实践
作者:互联网
我理解如何(和why)在JSX中添加空格,但我想知道什么是最佳实践或者是否有任何真正的区别?
将两个元素包裹在一个范围内
<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会让您拥有不间断的空间,所以您只能在必要时使用它.在大多数情况下,这会产生意想不到的副作用.
较旧版本的React,我相信所有那些在v14之前,会自动插入< span> < /跨度>当你在标签内有换行符时.
虽然他们不再这样做,但这是一种在您自己的代码中处理此问题的安全方法.除非你的样式专门针对跨度(一般的不良做法),否则这是最安全的路线.
根据你的例子,你可以将它们放在一条线上,因为它很短.在较长线的场景中,您应该这样做:
<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>
此方法对于自动修剪文本编辑器也是安全的.
另一种方法是使用{”},它不会插入随机HTML标记.在样式化,突出显示元素以及消除DOM中的混乱时,这可能更有用.如果您不需要向后兼容React v14或更早版本,那么这应该是您首选的方法.
<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>
标签:javascript,reactjs,react-jsx 来源: https://codeday.me/bug/20191004/1851504.html