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)
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,但代价是网页/用户的安全性具有潜在风险.如果其他人为你工作,我不会使用这个.
归档时间: |
|
查看次数: |
24316 次 |
最近记录: |