簡體   English   中英

React.js 新行和返回

[英]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"
}

這被添加到反應應用程序中:

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

問題是新行、制表符和回車不包括在內。 有誰知道一種語法,在這種語法中無需進行怪物搜索和替換(此 API 返回數千條記錄,我寧願不必遍歷每個記錄以插入"<br />"等)。

不幸的是,我認為 ReactJS 不支持開箱即用。 我發現了一些你可以在這里使用的東西—— 反應字符串中的換行符

這解決了我的問題:

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;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM