[英]How to sort/hide the sequence of the component according to the hash in react js?
我遇到了一个问题,其中有一个包含label, index, visible
值的哈希,我需要根据index
值对组件进行排序,如果visible为true
,则它应该为可见。
这些是我的组件:
render(){
return(
<GroupFeaturedCarousel {...this.props}/>
<GroupAssignmentCarousel {...this.props}/>
<GroupSharedCarousel {...this.props}/>
<GroupChannelCarousel {...this.props}/>
)
}
哈希数组是这样的:
myArray = [
{default_label: "Featured", index: 0, visible: true},
{default_label: "Assigned", index: 1, visible: true},
{default_label: "Shared", index: 2, visible: true},
{default_label: "Channels", index: 3, visible: true}]
我能想到的解决方法是使用_.sortBy(myArray, 'index')
但是我该如何实现呢?
需要同时考虑排序和可见性。
“哈希”是什么意思? 你是说数组吗?
如果我正确理解我,我会这样:
class X extends React.Component{ myArray = [{ component: GroupFeaturedCarousel, index: 0, visible: true }, { component: GroupAssignmentCarousel, index: 1, visible: true } ] render() { return this.myArray .filter(x => x.visible == true) .sort((a,b) => a.index - b.index) .map(({component: Component, index}) => ({ <Component key={index} {...this.props} /> }); } }
扩展数组项,使其看起来像这样:
{
default_label: 'foo',
index: 0,
visible: true,
component: FooComponent
}
然后渲染如下:
render() {
return <React.Fragment>
{ myArray
.filter(item => item.visible)
.sort((a,b) => a.index - b.index))
.map(item => {
const Component = item.component
return <Component {...this.props} key={item.index} />
}) }
</React.Fragment>
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.