有没有办法在react中做array.join [英] is there a way to do array.join in react
本文介绍了有没有办法在react中做array.join的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想使用类似于array.join的语法在数组的每个元素之间插入分隔符.
I'd like to inject a separator between each element of an array using an array.join-like syntax.
类似以下内容:
render() {
let myArray = [1,2,3];
return (<div>
{myArray.map(item => <div>{item}</div>).join(<div>|</div>)}
</div>);
}
我已经使用lodash.transform方法使它工作了,但是感觉很丑陋,我只想做.join(<some-jsx>)
,并在每个项目之间插入一个分隔符即可.
I've got it working using a lodash.transform approach, but it feels ugly, I'd like to just do .join(<some-jsx>)
and have it insert a separator in between each item.
推荐答案
您还可以使用reduce
在数组的每个元素之间插入分隔符:
You can also use reduce
to insert the separator between every element of the array:
render() {
let myArray = [1,2,3];
return (
<div>
{
myArray
.map(item => <div>{item}</div>)
.reduce((acc, x) => acc === null ? [x] : [acc, ' | ', x], null)
}
</div>
);
}
或使用片段:
render() {
let myArray = [1,2,3];
return (
<div>
{
myArray
.map(item => <div>{item}</div>)
.reduce((acc, x) => acc === null ? x : <>{acc} | {x}</>, null)
}
</div>
);
}
这篇关于有没有办法在react中做array.join的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文