首页 > 解决方案 > 在反应 jsx 元素数组值中添加新行

问题描述

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

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 这是第三个

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

我得到的是:
这是第一行。,第二个,这是第三个

参考

更新答案:

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

解决方案


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

推荐阅读