2016-12-27 70 views
0

我的貨櫃代碼如下。我從另一個組件調用它。我必須展開/摺疊出現在另一個列表下的列表。如何在React.js中單擊按鈕時隱藏列表下方的列表?

return this.props.labresult.map(test => { 
    return (
    <div> 
     <ul className='Result-list'> 
     <li key={test.testId}> 
      <div> 
      <div className='Result-list__title'> 
       <span> {test.testName}</span> 
      </div> 
      <div className='Flt-rt' > 
       <IconButton tooltip="Collapse"> 
       <ContentRemoveCircle /> 
       </IconButton> 
       <IconButton tooltip="Expand"> 
       <ContentAddCircle /> 
       </IconButton> 
      </div> 
      </div> 
      <div className='Clearfix' /> 
      <div className='Border-all'> 
      { 
       test.labresultList.map(result => { 
       return (
        <li key={result.labresultId} > 
        <div> 
         <div> 
         <IconButton tooltip="Edit" key={result.labresultId} onClick={() => this.props.editLabResult(result)}> 
          <EditorModeEdit /> 
         </IconButton> 
         <span> {result.loincCodeName} &nbsp;</span>   
         </div> 
         <div> 
         <span> <b>status:</b> {result.status}</span> 
         <span> {result.value}{result.uom} </span> 
         </div> 
        </div> 
        <div className='Clearfix' /> 
        </li> 
       ) 
       }) 
      } 
      </div> 
     </li> 
     </ul > 
    </div> 
); 
}); 

現在的CollapseExpandonClick我必須顯示/隱藏test.labresultList。我怎樣才能做到這一點?

+0

以下答案是否有意義? –

回答

2

首先,我建議將嵌套的div分解爲它們自己的組件,因爲它越複雜,嵌套就越多。我甚至建議將<li>標籤作爲自己的組件,並傳遞道具。

因此,它看起來更像是這樣的:

return this.props.labresult.map((test) => { 
    return (
     <div> 
      <ul className='Result-list'> 
       <Test key={test.testId} {...test} /> 
      </ul> 
     </div> 
    ) 
} 

,並在Test組件,你甚至可以掰開其他子組件。

<li> 
    <div> 
     <div className='Result-list__title'> 
      <span> {this.props.testName}</span> 
     </div> 
     {/*----- all other stuff here ------------*/} 
     <div className='Border-all'> 
      {this._renderLabResults()} 
     </div> 
    </div> 
</li> 

好的,回到原來的問題。有幾個方法可以做到這一點:

  • 如果您只使用組件狀態(即使用this.statethis.setState)做出collapsed布爾狀態,並默認爲false在構造函數中。當用戶單擊更改此狀態的按鈕時,可以根據該值篩選test.labresultList
  • 如果您使用像Redux這樣的狀態容器,則可以使用Redux狀態並分派一個操作。當用戶單擊更改此道具的按鈕時,可以根據傳入組件的Redux狀態中的值來過濾test.labresultList

對於簡單的事情collapsed布爾支柱我建議只使用組件狀態。它僅針對單個組件,並且不需要將此值保留在全局Redux狀態中。除非你因其他原因需要它。

Test構造:

this.state = { 
    collapsed: false, 
}  

,當用戶點擊一個按鈕,用於切換倒塌布爾使用setState像這樣:this.setState({collapsed: !this.state.collapsed})

_renderLabResults()使用條件,以使相應的子組件。

_renderLabResults() { 
    if (!this.state.collapsed) { 
        // Not collapsed...render the test result here 
    } 
    return null  // Collapsed...render nothing 
}      
相關問題