我试图创建一个包含多行字符串的表格,但是我的表格无法正确格式化该字符串。以下是JSX代码:
<td>
{arr.join('\n')}
</td>
这里是相应的HTML代码:
<td data-reactid=".xyz">Line 1
Line 2
Line 3
Line 4</td>
但在浏览器中看起来像这样:
发生了什么事情,如何使我的换行符出现?
我试图创建一个包含多行字符串的表格,但是我的表格无法正确格式化该字符串。以下是JSX代码:
<td>
{arr.join('\n')}
</td>
这里是相应的HTML代码:
<td data-reactid=".xyz">Line 1
Line 2
Line 3
Line 4</td>
但在浏览器中看起来像这样:
发生了什么事情,如何使我的换行符出现?
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>
white-space: pre
属性会保留文本中的换行符,但会导致文本不再自动换行。也就是说,如果文本很长,它将会超出容器边界。因此我建议使用 white-space: pre-wrap
,这样效果更好。 - Mirage\u000A
作为换行符。例如:<td>Line 1\u000ALine 2</td>
- ericsoco您有几个选项:
1)使用块级元素,例如div
或p
并逐行包裹。
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最少,但可能会危及网页/用户的安全。如果其他选项适用于您,我不会使用此选项。white-space
属性的提及是值得的。 - Zachary J Rollyson 当你真正需要时,在JSX中使用{'\n'}
。
尝试使用<pre>
元素或CSS属性white-space: pre-wrap;