通过执行以下操作,我尝试在react组件中的单独行上显示字符串数组:
<div>
{this.props.notifications.join('\n')}
</div>
然而,这似乎不起作用。this.props.notifications是我想要在div中呈现的字符串数组。有人知道我该怎么解决这个问题吗?
发布于 2018-01-11 21:46:07
如果使用<p />
来呈现每一行呢?
<div>
{this.props.notifications.map(txt => <p>{txt}</p>)}
</div>
这将在不同的段落中呈现每个元素。
发布于 2018-01-11 21:46:53
我希望每个字符串都在单独的一行上。
在渲染中使用Array/map()
:
<div>
{ this.props.notifications.map(notification => <p>{ notification }</p>) }
</div>
发布于 2018-01-11 21:43:16
您可以使用string literals或\n
。
但您需要将其与css规则相结合:
white-space: pre-line;
以下是一个包含字符串文字的运行示例:
const arr = ['this is line #1', 'this is line #2', 'this is line #3']
const App = () => (
<div className="line-break">
{
arr.map(str => {
return(`
${str}
`)
})
}
</div>
);
ReactDOM.render(<App />, document.getElementById('root'));
.line-break {
white-space: pre-line;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>
下面是一个使用\n
的运行示例
const arr = ['this is line #1', 'this is line #2', 'this is line #3']
const App = () => (
<div className="line-break">
{
arr.join('\n')
}
</div>
);
ReactDOM.render(<App />, document.getElementById('root'));
.line-break {
white-space: pre-line;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>
https://stackoverflow.com/questions/48215965
复制