jsx表忽略换行符

Eri*_*win 16 javascript reactjs react-jsx

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

<td>
  {arr.join('\n')}
</td>
Run Code Online (Sandbox Code Playgroud)

这里是相应的html:

<td data-reactid=".xyz">Line 1
Line 2
Line 3
Line 4</td>
Run Code Online (Sandbox Code Playgroud)

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

在此输入图像描述

发生了什么,我如何让我的新线出现?

Chr*_*ris 18

尝试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;
}
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)

  • 值得注意的是,`white-space:pre`将保留你的换行符,但它会导致你的文本不再换行.这意味着,如果它是一长串文本,它将延伸到元素之外.出于这个原因,我发现`white-space:pre-wrap`对我们来说效果更好. (4认同)

Wir*_*rie 17

你有几个选择:

1)使用块级元素,如div或a,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'));
Run Code Online (Sandbox Code Playgroud)

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'));
Run Code Online (Sandbox Code Playgroud)

3)如果您确定XSS/hack没有数据威胁,您可以使用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'));
Run Code Online (Sandbox Code Playgroud)

最后一个产生最少量的HTML,但代价是网页/用户的安全性具有潜在风险.如果其他人为你工作,我不会使用这个.


don*_*kup 12

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