Is there a way to have line breaks in text without using dangerouslySetInnerHTML?

老子叫甜甜 提交于 2021-02-10 07:49:06

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!