首页 > 解决方案 > React/MaterialUI:如何尊重字符串中的空格?

问题描述

尝试从 Material UI ( https://material-ui.com/api/typography/ )使用排版

目标是使保存的字符串中的新行和空格得到尊重。

这样具有前导空格和新行的示例将呈现为:

const svg = d3.select("#chart-area")
   .append("svg")  
   .attr("width", 400)
   .attr("height", 400)

如果我只是使用<Typography>{val}</Typography>,那么值会在一行中呈现,例如:

const svg = d3.select("#chart-area") .append("svg") .attr("width", 400) .attr("height", 400)

添加{{ whiteSpace: 'pre-line' }}使 Typography 至少尊重新行:

<Typography style={{ whiteSpace: 'pre-line' }}>{val}</Typography>

将字符串呈现为

const svg = d3.select("#chart-area")
.append("svg")
.attr("width", 400)
.attr("height", 400)

但是我们如何让组件尊重新行和前导空格?

标签: javascripthtmlreactjsmaterial-ui

解决方案


您可以使用预先格式化的文本元素而不是<Typography />

<pre>
  const svg = d3.select("#chart-area")
.append("svg")
.attr("width", 400)
.attr("height", 400)
</pre>

推荐阅读