[英]Render newline character in React
let arr = [{text: "1 x Coffee for 3,4 Euro \n\n3 x Coffee for 3,5 Euro"}]
I would like to parse the newline character( \n) so that every Coffee is displayed on its own line.我想解析换行符(\n),以便每个咖啡都显示在自己的行上。 Like:喜欢:
'1 x Coffee for 3,4 Euro'
'3 x Coffee for 3,5 Euro'
I tried:我试过了:
function FormatBody() {
return <> {`${arr[0].text.replace(/\n/g, "<br />")}`} </>
}
But that did not work.但这没有用。 Thanks for reading!谢谢阅读!
Instead of adding <br>
elements you could split the text on the line return, and then map
over that array and wrap each sentence in a paragraph element.除了添加<br>
元素之外,您还可以在行返回上拆分文本,然后在该数组上使用map
并将每个句子包装在一个段落元素中。
function Example({ data }) { function formatBody(text) { return text.split(/\n+/).map(p => <p>{p}</p>); } return ( <div> {formatBody(data[0].text)} </div> ); } const data = [{text: "1 x Coffee for 3,4 Euro \n\n3 x Coffee for 3,5 Euro"}] ReactDOM.render( <Example data={data} />, document.getElementById('react') );
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.production.min.js"></script> <div id="react"></div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.