2017-02-12 44 views
2

您好我正在玩ReactJS,並且發現這個非常棒的模式組件在模態中打開Videoes,但是當我將模態放到一個帶有多個鏈接的循環中並打開模式時,如果我有5個鏈接,它會打開5次。我做錯了什麼?ReactJS Modal在循環中打開多次

模態分量: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> 

回答

3

問題是,每個ModalComponent使用相同的狀態屬性isOpen,所以當你點擊任何鏈接時,它設置此屬性,並且每個ModalComponent都變爲打開狀態。您應該爲每種模式使用獨特的屬性(您可以使用您已經使用的屬性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 
     } 
    }); 
} 
+0

剛剛嘗試過你的想法,它的工作完美,它打開和關閉沒有問題!感謝您的解釋,我想我現在幾乎可以了!的xD – DbTheChain

0

原因是,使用的是單state變量保持modalopen/close狀態,它可以正常工作,但如果是多模態,則必須使用多個st吃值保持狀態,使用此:

在狀態定義isOpen作爲array

this.state= { 
    isOpen=[], 
} 

用此方法change的任何特定modal狀態:

openModal(index){ 
    let isOpen = this.state.isOpen.slice(); 
    isOpen[index] = true; 
    this.setState({isOpen}); 
} 

BindonClick方法中的各個模態的index方法:

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[i] || false} videoId='{frags.url}' /> 
        <button onClick= {this.openModal.bind(this,i)}>Open</button> 
       </li> 
      )}) 
      } 
     </div> 
    ) 
} 
+0

感謝您的快速答覆和真正偉大的解釋!它有效,第一個模式打開perfeclty,但是當我打開下一個模式時,它會打開兩個模式,比如新模式和前置模式。你有什麼線索爲什麼? :) – DbTheChain