【问题标题】:React.js New Line and ReturnsReact.js 换行和返回
【发布时间】:2021-08-25 15:55:47
【问题描述】:

我正在调用一个 API,该 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>

问题是新行、制表符和回车不包括在内。有谁知道在不进行怪物搜索和替换的情况下会尊重这一点的语法(此 API 返回数千条这样的记录,我不想遍历每条记录以插入 "&lt;br /&gt;" 等)。

【问题讨论】:

    标签: javascript reactjs parsing newline


    【解决方案1】:

    不幸的是,我认为 ReactJS 不支持开箱即用。我发现了一些你可以在这里使用的东西 - Newline in react string

    【讨论】:

      【解决方案2】:

      这解决了我的问题:

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

      【讨论】:

        猜你喜欢
        • 2011-10-25
        • 2021-01-15
        • 2021-07-03
        • 1970-01-01
        • 2021-12-25
        • 2013-09-12
        • 1970-01-01
        • 2018-05-10
        • 2014-12-06
        相关资源
        最近更新 更多