首页 > 解决方案 > 如何在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>

whered.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 />那会奏效吗?

标签: javascripthtmlreactjstext

解决方案


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

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

推荐阅读