ReactJS Modal 在循环中多次打开

DbT*_*ain 2 javascript modal-dialog reactjs

嗨,我正在玩 ReactJS,发现这个很棒的模态组件可以在模态中打开视频,但是当我将模态放在具有多个链接的循环中并打开模态时,如果我有 5 个链接,它会打开 5 次。我做错了什么?

模态组件:https : //github.com/appleple/react-modal-video

import React from 'react'
import ReactDOM from 'react-dom'enter code here
import ModalVideo from 'react-modal-video'

class App extends React.Component {
 constructor () {
    super()
    this.state = {
      isOpen: false
    }
    this.openModal = this.openModal.bind(this)
  }

  openModal () {
    this.setState({isOpen: true})
  }

      render () {
        return (
          <div>
            <ModalVideo channel='youtube' isOpen={this.state.isOpen} videoId='L61p2uyiMSo' />
            <button onClick={this.openModal}>Open</button>
          </div>
        )
      }
    }

    ReactDOM.render(
      <App />,
        document.getElementById('root')
    )
Run Code Online (Sandbox Code Playgroud)

我的带有模态组件的循环:

render(){
    return(
            <div>
                {(this.props.frag.all == null) ? null :
                  this.props.frag.all.map((frags, i) => {
                  return (
                  <li key={frags.id} className="group" id="" style={{width: 'calc(13% - 30px)'}}>
                    <ModalVideo channel='youtube' isOpen={this.state.isOpen} videoId='{frags.url}' />
                      <button onClick= {this.openModal.bind(this)}>Open</button>
                  </li>
                )})
              }
          </div>
Run Code Online (Sandbox Code Playgroud)

Bar*_*icz 5

问题是每个 ModalComponent 使用相同的 state 属性,isOpen因此当您单击任何链接时,它会设置此属性,并且每个 ModalComponent 都变为打开状态。您应该为每个模态使用唯一的属性(您可以使用您已经使用的 poperty key)。

<li key={frags.id} className="group" id="" style={{width: 'calc(13% - 30px)'}}>
    <ModalVideo channel='youtube' isOpen={this.state.isOpen[frags.id]} videoId='{frags.url}' />
    <button onClick= {this.openModal.bind(this, frags.id)}>Open</button>
 </li>
Run Code Online (Sandbox Code Playgroud)

还有你的方法:

 openModal (id) {
    this.setState({
       isOpen: {
          [id]: true
       }
    });
 }
Run Code Online (Sandbox Code Playgroud)