换行符在JSX表格中被忽略。

19

我试图创建一个包含多行字符串的表格,但是我的表格无法正确格式化该字符串。以下是JSX代码:

<td>
  {arr.join('\n')}
</td>

这里是相应的HTML代码:

<td data-reactid=".xyz">Line 1
Line 2
Line 3
Line 4</td>

但在浏览器中看起来像这样:

enter image description here

发生了什么事情,如何使我的换行符出现?


1
如果你只是在询问为什么(至少目前是这样),那么这就是一个重复的问题,与为什么浏览器将换行符呈现为空格?相同。 - Felix Kling
谢谢,我已经更新了问题。 - Eric Baldwin
4个回答

23
尝试在您的单元格样式中使用 white-space: pre;white-space: pre-wrap;(感谢 @Mirage)。

td {
  width: 150px;
}

.nopre {
  background-color: lightblue;
}

.withpre {
  background-color: lightgreen;
  white-space: pre;
}

.withprewrap {
  background-color: orange;
  white-space: pre-wrap;
}
<table><tr>

<td class="nopre">Line A
Line B
Line C
This is a cell with no whitespace setting</td>

</tr></table><table><tr>

<td class="withpre">Line 1
Line 2
Line 3
This is a cell with white-space: pre</td>

</tr></table><table><tr>
  
<td class="withprewrap">Line 1
Line 2
Line 3
This is a cell with white-space: pre-wrap</td>
  
</tr></table>


4
值得注意的是 white-space: pre 属性会保留文本中的换行符,但会导致文本不再自动换行。也就是说,如果文本很长,它将会超出容器边界。因此我建议使用 white-space: pre-wrap,这样效果更好。 - Mirage
如果您不想在JSX中使用空格,可以使用\u000A作为换行符。例如:<td>Line 1\u000ALine 2</td> - ericsoco
这会为我插入逗号,而不是换行。 - Aadi

18

您有几个选项:

1)使用块级元素,例如divp并逐行包裹。

var TextLines = React.createClass({      
    render: function() {
        var lines = this.props.lines;

        var formatted = lines.map(function(line) {
            return (<p>{line}</p>);
        });
        return (<div>{ formatted }</div>);
    }
});

var lines = ['line 1', 'line 2', 'line 3'];
React.render(<TextLines lines={ lines }/>, 
              document.getElementById('container'));

2) 使用带有 br 元素的 span:

var TextLines = React.createClass({      
    render: function() {
        var lines = this.props.lines;

        var br = lines.map(function(line) {
            return (<span>{line}<br/></span>);
        });
        return (<div>{ br }</div>);
    }
});

var lines = ['line 1', 'line 2', 'line 3'];
React.render(<TextLines lines={ lines } />,  
              document.getElementById('container'));

3) 如果您确定数据没有XSS /黑客威胁,您可以使用dangerouslySetInnerHTML,每行使用'br':

var TextLines = React.createClass({      
    render: function() {
        var lines = this.props.lines;
        var content = {
            __html: lines.join('<br />')
        };     
        return (<div dangerouslySetInnerHTML={ content } />);
    }
});

var lines = ['line 1', 'line 2', 'line 3'];
React.render(<TextLines lines={ lines } />, 
             document.getElementById('container'));
最后一个生成的HTML最少,但可能会危及网页/用户的安全。如果其他选项适用于您,我不会使用此选项。

考虑到@Chris的回答,我认为在这里添加有关CSS white-space属性的提及是值得的。 - Zachary J Rollyson

15

当你真正需要时,在JSX中使用{'\n'}


1
这个解决方案在React-Native中是默认的。当你想要将内部文本括在括号中(遵守ESLint规则“react/jsx-no-literals”)时,这个解决方案如何工作?我无法使用模板字符串正确地实现它。 - trysis

3

尝试使用<pre>元素或CSS属性white-space: pre-wrap;


只需添加<pre>标签并在文本底部添加空格即可。其他答案中的pre-wrap不适用。 - RealNmae

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接