javascript - react js中如何根据hash排序/隐藏组件的顺序?

标签 javascript reactjs

我遇到了一个问题,其中有一个包含 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} />
    });
  }
}

关于javascript - react js中如何根据hash排序/隐藏组件的顺序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54512166/

相关文章:

javascript - React Redux Form 文本区域上的字符计数器

javascript - 在 setState 之后使用 setTimeout 来避免异步问题

javascript - 将相机 W.R.T 3d 对象放置在 Three.js 中

javascript - 如何为 window.location.pathname 实现通配符

javascript - 如何在普通网站的多个地方使用 React

javascript - 如何在 React JS 的组件中通过 props 显示信息

javascript - 联系表单发送按钮抛出错误

c# - 在 ASP.NET 问题中使用 jQuery AjaxForm

javascript - 如果最初隐藏,则 Twitter 按钮不显示

javascript - 如何获取一个JS ID作为网站的后台页面?