React.js 新行和 Returns
React.js New Line and Returns
我正在调用一个 API 来响应具有一般形式的项目(对象):
{
"comment":"Here is a comment that has a new line \n, a return \r and a tab in it for this item: \r\tSome Item"
}
这被添加到 React 应用程序中:
<Item>{item.comment}</Item>
问题是新行、制表符和 returns 不包括在内。有谁知道一种语法,无需进行怪物搜索和替换(这 API returns 数千条记录,我宁愿不必遍历每个记录来插入 "<br />"
等)。
这解决了我的问题:
import React from 'react';
//styles
import './index.css';
/**
* Used to preserve whitespace for text values. For instance, \n, \r, and \t characters
* @param {Object} props
* @param {string} props.text The text you want to preserve whitespace from.
*/
function PreserveWhitespace({text}) {
return (
<span className="preserve-whitespace">
{text}
</span>
);
}
export default PreserveWhitespace;
和 CSS:
.preserve-whitespace {
white-space: pre-wrap;
}
不幸的是,我认为 ReactJS 不支持开箱即用。我在这里找到了可以使用的东西 - Newline in react string
我正在调用一个 API 来响应具有一般形式的项目(对象):
{
"comment":"Here is a comment that has a new line \n, a return \r and a tab in it for this item: \r\tSome Item"
}
这被添加到 React 应用程序中:
<Item>{item.comment}</Item>
问题是新行、制表符和 returns 不包括在内。有谁知道一种语法,无需进行怪物搜索和替换(这 API returns 数千条记录,我宁愿不必遍历每个记录来插入 "<br />"
等)。
这解决了我的问题:
import React from 'react';
//styles
import './index.css';
/**
* Used to preserve whitespace for text values. For instance, \n, \r, and \t characters
* @param {Object} props
* @param {string} props.text The text you want to preserve whitespace from.
*/
function PreserveWhitespace({text}) {
return (
<span className="preserve-whitespace">
{text}
</span>
);
}
export default PreserveWhitespace;
和 CSS:
.preserve-whitespace {
white-space: pre-wrap;
}
不幸的是,我认为 ReactJS 不支持开箱即用。我在这里找到了可以使用的东西 - Newline in react string