[英]React render a conditional div depending array
I have a html table inside a React component that is rendered with data mapped from an array, with day tags of the week that a service is active.我在 React 组件中有一个 html 表,该表使用从数组映射的数据呈现,并带有服务处于活动状态的星期几标签。 If the labels inside that array are Monday, Tuesday, Wednesday, Thursday and Friday, I need render an abbreviation like "Mon to Fri", instead the default render "label","label"... here is the snippet
如果该数组中的标签是星期一、星期二、星期三、星期四和星期五,我需要渲染一个缩写,如“星期一到星期五”,而不是默认渲染“标签”,“标签”......这是片段
<td>
{moment(start, 'HH:mm:ss').format('HH:mm')} /
{moment(end, 'HH:mm:ss').format('HH:mm') }
{ days.flatMap((days, i) => [
<div style={{paddingLeft:'2px', display: 'inline-block'}}>
{days.label},
</div>
]) }
</td>
The object days its like this:对象天它是这样的:
[
{
"label": "Mon",
"value": "1"
},
{
"label": "Tue",
"value": "2"
},
{
"label": "Wed",
"value": "3"
},
{
"label": "Thu",
"value": "4"
},
{
"label": "Fri",
"value": "5"
}
]
Edit: add a picture, its Spanish, but Lun = Monday, Mar= Tuesday, and so on...编辑:添加图片,它的西班牙语,但 Lun = 星期一,Mar = 星期二,依此类推...
I'm already rendering the week days selected, Monday, Wednesday and Friday, with this code:
我已经使用以下代码呈现选定的工作日,星期一,星期三和星期五:
{ days.flatMap((days, i) => [
<div style={{paddingLeft:'2px', display: 'inline-block'}}>{days.label},</div>
]) }
but, when user select the five days, Mon, Tue, Wed, Thu, Fri, I need a conditional render to match that particular case, any other case, should execute the code above.但是,当用户选择星期一、星期二、星期三、星期四、星期五这五天时,我需要一个条件渲染来匹配该特定情况,任何其他情况都应该执行上面的代码。
Thanks!谢谢!
Sounds like you just want to grab the first and last elements of the days
array and compute an abbreviated interval.听起来您只想获取
days
数组的第一个和最后一个元素并计算一个缩写的间隔。
const days = [{ "label": "Mon", "value": "1" }, { "label": "Tue", "value": "2" }, { "label": "Wed", "value": "3" }, { "label": "Thu", "value": "4" }, { "label": "Fri", "value": "5" } ]; const abbreviation = [days[0], days.length > 1 && days[days.length - 1]] .filter(Boolean) .map(({ label }) => label) .join(' to '); console.log(abbreviation);
If the original data has full-length day names, use the same but update what is mapped.如果原始数据具有完整的日期名称,请使用相同但更新映射的内容。
const days = [{ "label": "Monday", "value": "1" }, { "label": "Tuesday", "value": "2" }, { "label": "Wednesday", "value": "3" }, { "label": "Thursday", "value": "4" }, { "label": "Friday", "value": "5" } ]; const abbreviation = [days[0], days.length > 1 && days[days.length - 1]] .filter(Boolean) .map(({ label }) => label.slice(0,3)) .join(' to '); console.log(abbreviation);
Try this more simpler way试试这个更简单的方法
const days = [{ "label": "Mon", "value": "1" }, { "label": "Tue", "value": "2" }, { "label": "Wed", "value": "3" }, { "label": "Thu", "value": "4" }, { "label": "Fri", "value": "5" } ]; console.log(days[0].label+' to '+days[days.length-1].label)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.