Javascript 字符串不换行

Javascript string does not break in new lines

我试图在换行符中断开字符串,我的代码如下所示:

  return (
    <>
      {`${t('UserName')}: ${Username}\n 
        ${t('FirstName')}: ${FirstName}\n
        ${t('LastName')}: ${LastName}`}
    </>
  );

当我检查 HTML 时,它看起来像是换行:

但不幸的是,这不起作用..在 UI 中显示为:

明显排成一排..

试试这个

  return (
    <>
      {`${t('UserName')}: ${Username}`<br>
        `${t('FirstName')}: ${FirstName}`<br>
        `${t('LastName')}: ${LastName}`}
    </>
  );

目前,由于默认的 white-space 值为 normal

,换行符与其他白色 space 一样被处理

来自 MDN 网络文档:

white-space:normal - Sequences of white space are collapsed. Newline characters in the source are handled the same as other white space. Lines are broken as necessary to fill line boxes.

如果您确实必须使用 \n 进行布局,您可以使用 white-space: pre-line

white-space:pre-line - Sequences of white space are preserved. Lines are broken at newline characters, at <br>, and as necessary to fill line boxes.

document.getElementById("root").innerHTML="<div>123\n456</div>"
div {
   white-space: pre-line;
}
<div id="root"></div>

尝试给它一个css 属性“whiteSpace:'pre-wrap'”几天前我遇到了同样的问题它对我有用

您可能想将 React.Fragment shorthand 更改为 div?然后,添加行内样式:

return (
    <div style={{whiteSpace: 'pre-line'}}>
        {`${t('UserName')}: ${Username}\n 
        ${t('FirstName')}: ${FirstName}\n
        ${t('LastName')}: ${LastName}`}
    </div>
);