2017-08-06 28 views
3

我正在尝试使用map渲染多个react-bootsrap模态,但我无法这样做。用我现在的代码点击'View Details'按钮,可以同时激活所有的模态而不是打开相关的模态。下面是我的代码片段相关的模式:在react-bootstrap中正确渲染多个模态

render() { 
    const { accounts } = this.props; 
    const displayAccounts = Object.keys(accounts).filter(key => { 
     return accounts[key].info.type === 'student' 
    }).map(key => { 
     return (
     <tr key={key}> 
      <th>{accounts[key].info.name}</th> 
      <td>{accounts[key].info.email}</td> 
      <td><Button bsStyle='danger' onClick={() => this.props.removeAccount(key)}>Remove Account</Button></td> 
      <td> 
      <ButtonToolbar> 
       <Button id={key} bsStyle="primary" onClick={this.showModal}>View Details</Button> 
       <Modal 
       id={key} 
       show={this.state.show} 
       onHide={this.hideModal} 
       > 
       <Modal.Header closeButton> 
        <Modal.Title>Student Details</Modal.Title> 
       </Modal.Header> 
       <Modal.Body> 
        <Table responsive striped hover> 
        <thead> 
         <tr> 
         <th>Title</th> 
         <th>Details</th> 
         </tr> 
        </thead> 
        <tbody> 
         <tr> 
         <th>Name</th> 
         <td>{accounts[key].userDetails.name}</td> 
         </tr> 
         <tr> 
         <th>Education</th> 
         <td>{accounts[key].userDetails.education}</td> 
         </tr> 
         <tr> 
         <th>GPA</th> 
         <td>{accounts[key].userDetails.gpa}</td> 
         </tr> 
         <tr> 
         <th>Skills</th> 
         <td>{accounts[key].userDetails.skills}</td> 
         </tr> 
         <tr> 
         <th>Overview</th> 
         <td>{accounts[key].userDetails.skills}</td> 
         </tr> 
        </tbody> 
        </Table> 
       </Modal.Body> 
       <Modal.Footer> 
        <Button onClick={this.hideModal}>Close</Button> 
       </Modal.Footer> 
       </Modal> 
      </ButtonToolbar> 
      </td> 
     </tr> 
    ) 
    }) 

回答

1

尝试进行以下修改......

添加如下修改this.stateconstructor缓存稍后分配有效的模态指数。

this.state = { 
    ..., 
    activeModal: null, 
    ..., 
} 
this.clickHandler = this.clickHandler.bind(this); 
this.hideModal = this.hideModal.bind(this); 

添加/更改以下事件处理程序。 clickHandler接受点击事件以及将用于设置上述activeModal状态片段的索引。当反应发现状态改变时,它会调用render方法和新状态。这是React的Reactive性质。

clickHandler(e, index) { 
    this.setState({ activeModal: index }) 
} 

hideModal() { 
    this.setState({ activeModal: null }) 
} 

在你的map函数中做这样的事情。请注意0​​处理程序。使用箭头函数来捕获单击事件,并调用您的clickHandler,这是因为您也可以传递其他参数(在这种情况下为index)。一旦调用activeModal状态片段,组件将被重新渲染,在对show进行处理后,prop将评估为适当的clicked组件。

buttonArray.map((button, index) => { 
    <Button id={key} bsStyle="primary" onClick={e => this.clickHandler(e, index)}>View Details</Button> 
    <Modal 
     id={key} 
     show={this.state.activeModal === index} 
     onHide={this.hideModal} 
    /> 
}) 
+0

感谢您的解决方案。太棒了。你能解释一下代码吗?我是一名初学者。 –

+1

当然,我编辑了一些更多细节的答案,希望这有助于! –