我想創建一個多行字符串的表,但字符串沒有正確格式化我的表。這裏是JSX:新行字符被jsx表忽略
<td>
{arr.join('\n')}
</td>
這裏是相應的HTML:
<td data-reactid=".xyz">Line 1
Line 2
Line 3
Line 4</td>
但在瀏覽器中,它看起來像:
這是怎麼回事?如何讓我的換行符出現?
我想創建一個多行字符串的表,但字符串沒有正確格式化我的表。這裏是JSX:新行字符被jsx表忽略
<td>
{arr.join('\n')}
</td>
這裏是相應的HTML:
<td data-reactid=".xyz">Line 1
Line 2
Line 3
Line 4</td>
但在瀏覽器中,它看起來像:
這是怎麼回事?如何讓我的換行符出現?
你有幾種選擇:
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
元素:
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'屬性添加提及。 – 2016-09-08 21:52:58
這是一個HTML事情,換行符和空格是一樣的。 強制換行使用<br/>
標籤,如{arr.join('<br/>')}
。
默認情況下,React在字符串中轉義HTML。 – chirlu 2015-04-02 11:40:17
當你真的需要這個,在你的JSX裏面使用{'\n'}
。
此解決方案在默認情況下處於React-Native中。當你想要括號內的內部文本(遵守ESLint規則「react/jsx-no-literals」)時,這是如何工作的?我無法使它與模板字符串正常工作。 – trysis 2016-09-11 02:33:51
嘗試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>
嘗試使用<pre>
元素或CSS屬性white-space: pre-wrap;
如果你只問爲什麼(你目前至少做),這是一個重複[爲什麼瀏覽器將空行換行?](http://stackoverflow.com/q/588356/218196)。 – 2015-04-01 22:20:15
謝謝,我更新了這個問題。 – 2015-04-01 22:29:44