2017-07-12 38 views
0

我正在爲菜單導航編寫一個ReactJS應用程序,我在其中添加一個「選定」類,點擊div並從其他元素中刪除「選定」類。 現在我被困在如何從其他元素刪除類 這裏是我的代碼當我點擊任何其他元素時如何刪除ReactJS中的類?

<pre> 
**App.js** 

class App extends React.Component { 
    constructor(){ 
    super(); 
    this.state = { 
     active : "0", 
    } 
    } 
    clickHandler(index){ 

    } 
    render() { 
    let menu = this.props.menu; // menu is a array of page name e.g. ['home','about us','contact us'] 
    let style = 0; 
    return (
      {menu.map((menu, index) => 
      List clickHandler={this.clickHandler.bind(this, index)} index={index} key={index} menu={menu} 

      )} 
    ); 
    } 
} 

export default App; 


** list.js ** 

import React from 'react'; 

class List extends React.Component{ 
    constructor(props){ 
     super(props) 
     this.state = { 
      focused : "0" 
     } 
    } 
    clickMe(index){ 
     let style = ""; 
     this.setState({focused: index}); 
     if(this.state.focused == index){ 
      console.log(index); 
      style = "selected"; 
     } 
     this.props.clickHandler(); 

    } 
    render(){ 
     let style = ""; 
     if(this.state.focused === this.props.index){ 
      style = "selected"; 
     }else{ 
      style = ""; 
     } 
     return li className={style} onClick={this.clickMe.bind(this, this.props.index)}>{this.props.menu} /li> 
    } 
} 

export default List; 

</pre> 

回答

1

我的建議是創建兩個組件

1)名單,該組件將有選擇的內部狀態數/指數/重點項目。作爲道具,這個組件將獲得一系列物品。在渲染方法中,你可以渲染父標籤< ol>和</ol>,並且在該標籤中,可以在項目的foreach循環列表中進行管理,基於索引狀態和索引,在foreach循環中可以計算是否選擇項目。此組件將具有處理程序來更改此處理程序的選定索引,您必須將其傳遞給項目組件。

2)第二組分項目將呈現< li>標籤作爲正反該組件將來自陣列並用作從父List組件回調,也標誌,如果選擇了項獲得項目(假/真)。

當用戶點擊項目比來自List組件的處理程序將被稱爲父狀態的變化狀態比整個列表將被重新呈現。

確保第二個組件Item已經實現了componentWillReceiveProps(nextProps)方法。當選定的道具改變時可以渲染

相關問題