2017-02-12 4 views
2

こんにちは私はReactJSを使いこなしています。この素晴らしいモーダルコンポーネントがモーダルでビデオを開くのがわかりましたが、モーダルを複数のリンクを持つループの中に入れてモーダルを開くと、私は5つのリンクがあれば5回開いています。何が間違っていますか?ReactJSループが複数回開いているとき

モーダルコンポーネント:モーダルコンポーネント内で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が開きます。各モーダルに固有のプロパティを使用する必要があります(既に使用している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> 

そして、あなたの方法:

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

ちょうどあなたのアイデアを試して、それは完璧に働いた、それは問題なしで開閉する!説明をくれてありがとう、私は今それをほとんど持っていると思う! xD – DbTheChain

0

理由は、あなたが、modalopen/close状態を維持するために、単一のstate変数を使用していています1つは正しく動作しますが、複数のモーダルの場合は、複数のst状態を維持するための値を食べ、これを使用:change

this.state= { 
    isOpen=[], 
} 

使用この方法を任意の特定のmodalのステータス:

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

Bind

状態でarrayとしてisOpen定義各モードのindexは、onClickの方法:

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

素早く答えてくれてありがとうと本当に素晴らしい解説!最初のモーダルは完璧に開きますが、次のモードを開くと、新しいモーダルや前のような2つのモーダルが開きます。なぜあなたは何か手がかりがありますか? :) – DbTheChain

関連する問題