繁体   English   中英

如何在JS中强制添加换行符

[英]How to force add line break in JS

我有一个从 API 获取数据的反应应用程序。 获取的数据是一个字符串。

这种字符串的一个例子是,

TicTacToe\n
This is a simple tic-tac-toe game.\n
The player plays against an AI, which uses minimax algorithm to find the best logical move.\n
The player starts with 'X' and the AI plays 'O'.\n
It's probably impossible to win this game.

由于有\n ,我自然希望它会在 html 中添加新行。

这是 html,

<section className="intro">{d.about && d.about}</section>

其中d.about包含带有\n字符的字符串。

但是 html 简单地显示为,

TicTacToe This is a simple tic-tac-toe game. The player plays against an AI, which uses minimax algorithm to find the best logical move. The player starts with 'X' and the AI plays 'O'. It's probably impossible to win this game.

如何添加换行符? 从 api 获取后,是否需要将每个\n替换为<br /> 那会奏效吗?

const strs = str.split('\n').filter(s => s);

return <div>
   {strs.map(e => <>{e}<br/></>)}
</div>;

通过将所有\n替换为<br />来尝试此操作,您可以根据您的要求使用dangerouslySetInnerHTML直接绑定到 dom。

export default function App() {
  let str = `TicTacToe\n
  This is a simple tic-tac-toe game.\n
  The player plays against an AI, which uses minimax algorithm to find the best logical move.\n
  The player starts with 'X' and the AI plays 'O'.\n
  It's probably impossible to win this game.`;
  let updated = str.replaceAll("\n", "<br />");

  return (
    <div className="App">
      <div dangerouslySetInnerHTML={{ __html: updated }} />
    </div>
  );
}

现场演示

除了用<br/>标签替换新行之外,您还可以使用 CSS 来调整空格的呈现方式。

 const text = `TicTacToe\n This is a simple tic-tac-toe game.\n The player plays against an AI, which uses minimax algorithm to find the best logical move.\n The player starts with 'X' and the AI plays 'O'.\n It's probably impossible to win this game.`; document.querySelector(".intro").innerText = text;
 .intro { white-space: pre; }
 <section class="intro"></section>

暂无
暂无

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

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