使用非中断空格的 ReactJS 呈现字符串

我有一些道具,有一个字符串,可以包含字符,如 & 。 它还包含空格。我想用  替换所有的空格。

有什么简单的方法吗?请记住,我不能仅仅使用这种语法进行渲染:

<div dangerouslySetInnerHTML={{__html: myValue}} />

因为我必须首先用它们的标记替换任何 HTML 实体。我不想这样做,这似乎太低级。

我能做到吗?

79463 次浏览

So you have a value like this "Hello world", and we'll say it's in this.props.value.

You can do this:

var parts = this.props.value.split(" "), array = [];
for (var i=0; i<parts.length; i++){
// add the string
array.push(<span key={i * 2}>{parts[i]}</span>);
// add the nbsp
array.push(<span key={i * 2 + 1}>&nbsp;</span>);
}


// remove the trailing nbsp
array.pop();


return <div>{array}</div>;

jsbin

Instead of using the &nbsp; HTML entity, you can use the Unicode character which &nbsp; refers to (U+00A0 NON-BREAKING SPACE):

<div>{myValue.replace(/ /g, "\u00A0")}</div>

I know this is an old question, and this doesn't exactly do what you asked for, but rather than editing the string, what you want to achieve is probably be solved better using the CSS white-space: nowrap attribute:

In html:

<div style="white-space: nowrap">This won't break lines</div>

In react:

<div style=\{\{ whiteSpace: 'nowrap' }}>{myValue}</div>

If you want to display a pretty xml:

var str = "<test>\n\t\t<value>1</value>\n</test>\n".replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/\t/g, "\u00a0").replace(/\n/g, '<br/>');
return (
<div dangerouslySetInnerHTML=\{\{__html: str}} ></div>
)

Well it's very hard to type on here without it disappearing, so I'm adding a little whitespace so everyone can see it. If you remove the whitespace from this tag < nbsp />, then you'll be able to use a non-breaking space in React.

React translates this JSX tag into a non-breaking space. Weird quirk: This must also be used on the same line as the text you want to space. Also, non-breaking spaces with this tag don't stack in React.

To remove space in between string, below code works for me. eg: "afee dd " result: "afeedd"

{myValue.replace(/\s+/g, '')}

In my opinion, the best way to display &nbsp; is to print it explicitly in the code. (It is sad that react does not support such simple, basic, features out of the box.) If react's jsx throws error, it means nbsp was put incorrectly into code.

Simple rule is that all special characters should be wrapped with tag.

In most cases it's just possible to put it as it is:

return <span>{n}&nbsp;followers</span>;

But, if you want to add something like that:

// this will cause an error
{number > 0 && (<strong>{number}</strong>&nbsp;)}

you need to wrap part with nbsp with parent tag (for example, with empty):

{number > 0 && (
<>
<strong>{number}</strong>
&nbsp;
</>
)}

This might be useful in cases when special character is need only in some cases (when number is greater than 0, for example).