首页 > 解决方案 > React:在本地化文本中插入换行符

问题描述

我从 JSON 文件获取本地化文本并将其显示到页面,我的问题是\n<br>符号被忽略。

我在这里制作了一个代码沙箱,以显示文本如何不超过一行。

import * as React from "react";
import { render } from "react-dom";

const App: React.FC = props => {

  const Translations: {
    [key: string]: {
      fname: string;
    };
  } = {
    en: {
      fname: "I want to insert a break in this line of text so it shows on two lines \n doesnt work and <br> does either",
    },
    cn: {
      fname: "我想在这一行文本中插入一个中断,以便在两行中显示\ n不起作用,而&lt;br>可以",
    }
  };

  const txt = Translations["en"];


  return (
    <div className="App">
      <p>{txt.fname}</p>
    </div>
  );
};

const rootElement = document.getElementById("root");
render(<App />, rootElement);

标签: reactjs

解决方案


使用 CSS 属性white-space: pre-line <p style={{ whiteSpace: "pre-line" }}>{txt.fname}</p>


推荐阅读