簡體   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