首页 > 解决方案 > 有没有办法将换行符放入 JSX 字符串中,以便它们显示在 HTML 中

问题描述

所以我想要一个字符串显示多行,如下所示:

const str = "Hi\n\there\nBob"
let jsxElement = (<div>{str}</div>)

应该jsxElement像这样显示:

Hi
there
Bob

我试过\nand \r\nand &nbspand and <br>and <br />。有任何想法吗?

标签: javascripthtmljsx

解决方案


您可以这样做<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>
    )
  }

推荐阅读