问题
I need to replace \n
to <br>
. But it is taking this as in text.
How can I do that without using dangerouslySetInnerHTML
?
回答1:
var yourNewValueWithBr = yourOldValue.replace(/\n/g,"<br />");
After replacing this text, you will need to use dangerouslySetInnerHTML to render it as HTML.
回答2:
Insert the text as you normally would, and fix the line breaks with CSS:
white-space: pre-wrap;
Don't use dangerouslySetInnerHTML
unless you really have to.
回答3:
This solution replaces \n
to <br>
and works without dangerouslySetInnerHTML
:
render: function() {
var lines = this.props.text.split("\\n").map(function(line, n){
return (n == 0) ? [line] : [<br />, line];
});
return <div>{lines}</div>;
}
But if you need HTML formatting, and you're sure that your text is safe from XSS, I would recommend to stick with dangerouslySetInnerHTML
and a regex replace like Chris Hawkes said.
回答4:
You could use style={{whiteSpace: 'pre-wrap'}}
for the wrapping div.
Now you will break line without dangerouslySetInnerHTML
and <BR>
You can check browser compatibility over here: CSS SPEC
来源:https://stackoverflow.com/questions/31001066/is-there-a-way-to-have-line-breaks-in-text-without-using-dangerouslysetinnerhtml