换行符'\n'在html、vue、react中如何识别

2,336 阅读1分钟

我好友问我一个问题。看下图。

c082e49a69dc264a0f7dd7bc8b5e5bd.jpg

就是他在原生html测试white-space: pre-line没用。然后我就总结一下

1.原生html 下面的写法都不能识别white-space: pre-line

<h2 style="white-space: pre-line;">test\nhtml</h2>
<h2 style="white-space: pre-line;">'test\nhtml'</h2>
<h2 style="white-space: pre-line;">'test"\n"html'</h2>

解决办法:

(1)正则将\n匹配</br>

<body>
    <h2 style="white-space: pre-line;">test\nhtml</h2>
    <script>
        //使用正则将\n替换成<br/>标签
        const h2 = document.querySelector('h2')
        h2.innerHTML =  h2.innerHTML.replace(/\\n/g,'<br>') //注意正则是/\\n/g
        //也可以分割字符串然后再拼
        //h2.innerHTML =  h2.innerHTML.split('\\n').join("<br>")//注意\\n
    </script>
</body>

(2) 获取到标签,用html赋值

<body>
    <h2 style="white-space: pre-line;">test\nhtml</h2>
    <script>
        const h2 = document.querySelector('h2')
        h2.innerHTML = 'test\nhtml'
    </script>
</body>

2.vue vue中在scrpit中定义变量str,在html中用{{str}}渲染就行

<template>
  <div class="test">
    <h2 style="white-space: pre-line">{{ str }}</h2>
  </div>
</template>

<script setup lang="ts">
let str = 'test\nvue'
</script>

3.react

const str = 'test\nreact'
return <h1 style={{ whiteSpace: 'pre-line' }}>{str}</h1>

总结:html没法识别\n,可以转换成<br>标签,或者在js里操作。