2016-09-07 123 views
2

我有兩個組件正在加載一些數據。我想是的鏈接,輸出是這樣的:使用道具切換導航列表,嵌套數組/對象

  • 1組
    林卡LinkB的

但它這樣做

  • 1組
    林卡
  • 1組
    LinkB上

我能理解它是關於如何使用我的地圖以及我如何返回數據,但我無法弄清楚如何解決它並讓點擊處理程序爲組工作。

const navList = [ 
    { 
    "GroupName": "group1", 
    "links": [ 
     {"name": "link0a","id": "434"}, 
     {"name": "link0b","id": "342"} 
    ] 
}, 
{ 
    "GroupName": "group2", 
    "links": [ 
     {"name": "link1a","id": "345"}, 
     {"name": "link1b","id": "908"} 
    ] 
    } 
] 

class Nav extends Component { 

    constructor(props) { 
    super(props); 
    this.state = { 
     openItem: null 
    } 

    this.toggleClick = this.toggleClick.bind(this); 
    } 

    toggleClick(item, index, event) { 
    event.preventDefault() 
    if (index === this.state.openItem) { 
     this.setState({openItem: null}) 
    } else { 
     this.setState({openItem: index}) 
    } 
} 

render() { 
    return (

      <ul> 
       {navList.map((section, i) => { 
        const links = section.links.map((item, index) => { 
         const isOpen = this.state && this.state.openItem === index 

         return <NavItem title={section.GroupName} children={item.name} onClick={this.toggleClick.bind(null, item, index)} open={isOpen} /> 
        }) 

        return links 
       })} 
      </ul> 

    ) 
    } 
} 

class NavItem extends Component { 
    render() { 
    const toggleClass = this.props.open ? 'is-open' : '' 
    return (
     <li> 
      <h2 onClick={this.props.onClick}>{this.props.title}</h2> 
      <ul className={toggleClass}> 
       <li>{this.props.children}</li> 
      </ul> 
     </li> 
    ) 
    } 
} 

export default NavItem 

回答

1

NavLink刪除{this.props.title}在你上面貼的render()功能移動。否則,每次渲染NavLink時,都會顯示標題。不要忘記移動您的onClick處理程序。

這是基於你的jsfiddle工作示例:https://jsfiddle.net/lustoykov/n21Lspm3/1/

+0

謝謝,我曾經試過,但它打破了點擊處理 – Fox

+0

這是正確的,你必須還要移動單擊處理 – lustoykov

+0

我想,也可是我不能不能讓它工作 – Fox