换行符 - React Prop

Line Break - React Prop

我有一个组件<Ren1 text="Line1\nLine2\nLine3" /> ...

function Ren1({text}){
  return <p>{text}</p>;
}
export default Ren1

如何在 \n 来自数据库时添加换行符?

需要输出:

Line1
Line2
Line3

提前感谢您的帮助

您可以创建一个包含实际文本行的数组 split(即 const lines = text.split('\n'))。

然后你可以映射这个数组来渲染 单独行。

lines.map(line => ...)

拆分“\n”上的文本属性并将结果数组映射到具有 br 元素的 Fragment 内的 p 标记。

function Ren1({ text }) {
  return (
    <p>
      {text.split("\n").map((line, index) => (
        <React.Fragment key={index}>
          {line}
          <br />
        </React.Fragment>
      ))}
    </p>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(
  <Ren1 text="Line1\nLine2\nLine3" />,
  rootElement
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.13.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.13.1/umd/react-dom.production.min.js"></script>
<div id="root"></div>

您可以在不拆分文本值的情况下进行。

首先,在传递 text 属性时将花括号括起来:

<Text text={"One \n Two \n Three"} />

然后使用whiteSpace: "pre-line"样式

<div style={{ whiteSpace: "pre-line" }}>{props.text}</div>

sandbox