jsx 表忽略的换行符

IT技术 javascript reactjs react-jsx
2021-05-04 03:11:09

我正在尝试使用多行字符串创建一个表,但是我的表没有正确格式化该字符串。这是jsx:

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

这是相应的html:

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

但在浏览器中它看起来像:

在此处输入图片说明

发生了什么以及如何让我的换行符出现?

4个回答

尝试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>

你有几个选择:

1) 使用块级元素,例如div或 ap并包裹每一行。

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元素的跨度

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/hacks 的威胁,您可以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 最少,但代价是可能危及网页/用户的安全。如果其他人为你工作,我不会使用这个。

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

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