[英]split a string by newline in react
I have a json string for order.expeditionPlaces which is formatted like: 我有一个用于order.expeditionPlaces的json字符串,其格式如下:
"expeditionPlaces": "Place1, Place2, Place3"
I am able to split the data but I can't get the string to go onto a new line as html tags are escaped within react 我能够拆分数据,但是由于html标签在react中被转义,所以我无法使字符串进入新行
{order.expeditionPlaces ? order.expeditionPlaces.split(",").join("<br>") : ""}
should display: 应显示:
Place1
Place2
How can I re-write this so the string splits onto new lines? 如何重新编写此代码,以便字符串拆分为新行?
My current code is 我当前的代码是
if (this.state.possibleOrders && this.state.possibleOrders.length > 0) {
this.state.possibleOrders.forEach((order, index) => {
possibleOrders.push(<tr key={index}>
<td>{order.orderId}</td>
<td>{order.orderState}</td>
<td>{order.expeditionPlaces ? order.expeditionPlaces.split(",").join("<br>") : ""}</td>
<td>{order.sortingBufferPlaces}</td>
</tr>);
});
}
In your case JSX does not interpret "<br />"
as a HTML tag
, but as a string
, so 在您的情况下,JSX不会将"<br />"
解释为HTML tag
,而是解释为string
,因此
<td>
{
order.expeditionPlaces
? order.expeditionPlaces.split(",").join("<br>")
: ""
}
</td>
should be 应该
<td>
{
order.expeditionPlaces
? order.expeditionPlaces.split(",").map(place => <p> {place} </p>)
: ""
}
</td>
Your actual code returns a string when you need a react component :) 当您需要React组件时,您的实际代码将返回一个字符串:)
This code should work (not tested, might need some ajustments) 此代码应该可以工作(未经测试,可能需要一些调整)
if (this.state.possibleOrders && this.state.possibleOrders.length > 0) {
this.state.possibleOrders.forEach((order, index) => {
possibleOrders.push(<tr key={index}>
<td>{order.orderId}</td>
<td>{order.orderState}</td>
<td>
{(order.expeditionPlaces || []).split(",").map(function(place, i) {
return <p key={i}>place</p>
})}
</td>
<td>{order.sortingBufferPlaces}</td>
</tr>);
});
}
-EDIT replace -编辑替换
<p>
with whatever needed 无论需要什么
<div key={i}>place<br/></div>
will work too 也会工作
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.