【问题标题】:adding new lines in react jsx element array values在反应jsx元素数组值中添加新行
【发布时间】:2018-11-15 20:10:01
【问题描述】:

在反应中显示值时尝试添加新行。
谁能告诉我我错过了什么?
这是我的代码

const qList = qs.map(
    (question, idx) => (<div key={idx}>{idx>0?<hr />:<span />}{idx+1 + '. ' + 
    question.split('\n').map((item) => {return (item);})}</div>)
  );

  return (
    <div style={{ width: '100%' }}>
      { qList }
    </div>
  );

问题数据
这是第一行。\n第二行\n这是第三行

预期结果
这是第一行。
第二行
这是第三行

我得到了什么
这是第一行,第二行,第三行

reference

更新答案:

const qList = qs.map((question, idx) => (
        <div key={idx}>
          {idx>0?<hr />:<span />}
          {<span>
            {idx+1 + '. '}
          </span>}
          {
            question.split('\n').map(item =>(
              <span>
                {item}
                <br />
              </span>
            ))
          }
        </div>
      ));

return (
    <div style={{ width: '100%' }}>
      { qList }
    </div>
  );

【问题讨论】:

    标签: reactjs


    【解决方案1】:
    class Application extends React.Component {
    render() {
      let qlist = ["this is line first line.\nThe second\n and this is third"];
      return (
        <div style={{ width: '100%' }}>
          { 
            qlist.map((qs, idx) => (
              <div key={idx}>
                {
                  qs.split("\n").map(item => (
                    <span>
                      {item}
                      <br/>
                    </span>
                  ))
                }
              </div>
             ))
          }
        </div>
      );
    }
    }
    

    【讨论】:

      【解决方案2】:

      HTML 不理解 \n。请改用&lt;br /&gt;

      这应该会有所帮助:

      question.split('\n').map((item) => {return <span> {item} + <br /></span>;})}</div>)
      

      【讨论】:

      • 我也试过了,但没有运气。你能用代码示例更新一下吗?
      • 感谢您的帮助。但它不起作用。给
        而不是换行
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-09-11
      • 1970-01-01
      • 2020-03-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-05-31
      相关资源
      最近更新 更多