javascript - 有没有办法将换行符放入 JSX 字符串中,以便它们显示在 HTML 中
问题描述
所以我想要一个字符串显示多行,如下所示:
const str = "Hi\n\there\nBob"
let jsxElement = (<div>{str}</div>)
应该jsxElement
像这样显示:
Hi
there
Bob
我试过\n
and \r\n
and  
and and <br>
and <br />
。有任何想法吗?
解决方案
您可以这样做<React.Fragment>
:
render() {
const test = "Hi\n\there\nBob";
return (
<div>
{test.split('\n').map((item, index, arr) => {
return <React.Fragment>
{item}{index < arr.length - 1 && <br/>}
</React.Fragment>
})}
</div>
)
}
推荐阅读
- nservicebus - 在移动到 NServiceBus 中的 ErrorQueue 之前,在命令处理程序中查找重试计数并调用外部服务
- android - 为什么 TTakePhotoFromCameraAction.OnDidFinishTaking 事件在 Android 10 上不起作用?
- python - 我的项目正在使用 google colab 但未使用 pycharm
- woocommerce - 如何在woocommerce中通过tagId获取特定标签
- mysql - 如何从一列包含用逗号分隔的值的特定表中进行选择 [SQL]
- python - 为什么我的第二个字符串替换正在执行但第一个没有?
- javascript - Docker compose:从不同容器中的前端 javascript 请求到达后端
- flutter - 我需要将数据从小部件传递到新的小部件而不是 Flutter 中的屏幕
- laravel - Laravel 使用 delete() 调用删除错误的模型
- apache-kafka - KSQL 创建表作为选择