ReactJS Modal在循环中多次打开 [英] ReactJS Modal opening multiple times when in a Loop

查看:382
本文介绍了ReactJS Modal在循环中多次打开的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在玩ReactJS,发现了这个很棒的Modal Component可以在Modal中打开Videoes,但是当我将Modal放入具有多个链接的循环中并打开Modal时,如果我有5个,它就可以打开5次链接.我该怎么办?

Hi I am playing around with ReactJS, and found this awesome Modal Component to open Videoes in a Modal, but when I put the Modal inside a loop with multiple links and open the modal, it open like 5 times if I have 5 links. What do I do wrong?

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

Modal Component: 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')
    )

我的循环中包含模态组件:

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>

推荐答案

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

The problem is that each ModalComponent uses the same state property isOpen so when you click on any link it sets this property and each ModalComponent becomes open. You should use unique property for each modal (you can use poperty which you already uses as 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>

以及您的方法:

 openModal (id) {
    this.setState({
       isOpen: {
          [id]: true
       }
    });
 }

这篇关于ReactJS Modal在循环中多次打开的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆