问题
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?
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')
)
My Loop with the Modal Component Inside:
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>
回答1:
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>
And your method:
openModal (id) {
this.setState({
isOpen: {
[id]: true
}
});
}
回答2:
Reason is, you are using single state
variable to maintain open/close
status of modal
, it will work properly for one, but in case of multiple modals, you have to use multiple state values to maintain the statuses, Use this:
Define isOpen
as an array
in state:
this.state= {
isOpen=[],
}
Use this method to change
the status of any particular modal
:
openModal(index){
let isOpen = this.state.isOpen.slice();
isOpen[index] = true;
this.setState({isOpen});
}
Bind
the index
of each modal in onClick
method:
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>
)
}
来源:https://stackoverflow.com/questions/42187381/reactjs-modal-opening-multiple-times-when-in-a-loop