简体   繁体   English

React.js 新行和返回

[英]React.js New Line and Returns

I'm calling an API that responds with items (objects) that have the general form:我正在调用一个 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"
}

This gets added to the react app:这被添加到反应应用程序中:

<Item>{item.comment}</Item>

The problem is the new line, tab and returns aren't included.问题是新行、制表符和回车不包括在内。 Does anyone know a syntax where this will be respected without a monster search and replace (this API returns thousands of these records, I'd prefer not to have to iterate over each one to insert "<br />" etc).有谁知道一种语法,在这种语法中无需进行怪物搜索和替换(此 API 返回数千条记录,我宁愿不必遍历每个记录以插入"<br />"等)。

Unfortunately, I don't think ReactJS supports this out of the box.不幸的是,我认为 ReactJS 不支持开箱即用。 I found something that you can use here - Newline in react string我发现了一些你可以在这里使用的东西—— 反应字符串中的换行符

This solved my problem:这解决了我的问题:

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;

And the CSS:和 CSS:

.preserve-whitespace {
  white-space: pre-wrap;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM