简体   繁体   English

为什么在我的情况下换行符不起作用?

[英]Why new line escape character doesn't work in my case?

This is the line that doesn't work: 这行是行不通的:

const modalContent = () => `First line.\nSecond line?`;

I use it in React app in my component. 我在我的组件的React应用程序中使用它。

The new line is created in the string: 在字符串中创建新行:

 const modalContent = () => `First line.\\nSecond line?` console.log(modalContent()); 

… but a new line in HTML is treated just like any other kind of white space. …但是HTML中的新行与其他任何空白一样。

 First line. Second line? 

You need a <br> element instead of a new line, or CSS which sets white-space to a value where new lines are significant (such as pre ). 您需要一个<br>元素而不是换行符,或者需要一个CSS来将white-space设置为新行有效的值(例如pre )。

 First line.<br> Second line? 

In normal HTML the line-break is simply handled like a normal space. 在普通的HTML中,换行符的处理就像普通的空格一样。 There are two solutions. 有两种解决方案。

  1. You tell the surrounding html element with css that line-breaks and whitespaces are important. 您使用CSS告诉周围的html元素,换行符和空格很重要。 This is done fe by setting the style white-space to pre . 这是通过将样式white-space设置为pre

  2. You set the return-value of your function not to a string but to a jsx. 您可以将函数的返回值设置为一个jsx而不是字符串。 Then you can use a br element for a line-break: 然后,您可以将br元素用于换行符:

const modalContent = () => <span>First line.<br/>Second line?</span>;

Because you are using the backtick. 因为您正在使用反引号。 This resembles a template string in ES6. 这类似于ES6中的模板字符串。 It will respect any empty lines in the actual string. 它将尊重实际字符串中的任何空行。 \\n Will work in a regular string with single or double quotes \\ n适用于带单引号或双引号的常规字符串

So: 所以:

 const multi = ` this is multiline text `; const text = "this is not \\nmultiline\\ntext"; console.log(multi); console.log(text) 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM