【问题标题】:Is there a way to get newlines into JSX strings so that they display in HTML有没有办法将换行符放入 JSX 字符串中,以便它们显示在 HTML 中
【发布时间】:2019-06-24 23:14:33
【问题描述】:

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

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

应该像这样显示jsxElement

Hi
there
Bob

我试过\n\r\n&amp;nbsp&lt;br&gt;&lt;br /&gt;。有什么想法吗?

【问题讨论】:

  • 与 JSX 无关,你需要用 CSS 解决这个问题 - just like in Angular
  • 这真的很好用,谢谢

标签: javascript html jsx


【解决方案1】:

您可以像这样使用&lt;React.Fragment&gt; 执行此操作:

  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>
    )
  }

【讨论】:

    【解决方案2】:

    \n 将其放入 div 时将不起作用。我看到您希望在每一行中显示单个单词。我将这样做的一种方法是用 space(" ") 拆分字符串并映射结果数组。像这样的。

      let splitArray = str.split(" ");
      splitArray.map( (s) => (
              <div>{s}</div>
     ))
    

    如果您不喜欢生成多个 div,也可以使用 &lt;Fragment&gt;

    【讨论】:

      【解决方案3】:

      您不能直接设置包含html 的插入字符串,而是让您使用dangerouslySetInnerHTML 要附加html 作为字符串的属性

      <div dangerouslySetInnerHTML={{__html:"Line1</br>Line2</br>Line3"}}></div> 
      

      第二种方法是你使用这个函数

        appendMiltilineString = (str) => {
          str = str.split('\n')
          return (<>
              {str.map(line=>
              (<>
                  {line}<br></br>
              </>))}
            </>)
        }
       {this.appendMiltilineString('Line1\nLine2\nLine3')}
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-04-21
        • 1970-01-01
        • 1970-01-01
        • 2022-01-22
        • 1970-01-01
        相关资源
        最近更新 更多