我试图在 React 中循环制作弹出窗口,但我不知道如何只打开一个触发元素。
this.props.Videos.map((video) => {
return (
<div onClick={this.onClick}>
<img src="https://blog.xenproject.org/wp-content/uploads/2014/10/Testing.jpg" alt=""/>
<h3>Text</h3>
<div style={{display: this.state.videoPopup === true ? "block" : "none"}}>
<video data-setup='{ "techOrder": ["youtube"], "sources": [{ "type": "video/youtube", "src": ""}] }'
className="video-js vjs-default-skin"
controls>
</video>
</div>
</div>
);
})) : null
OnClick 像这样改变状态:
this.setState({
videoPopup: !this.state.videoPopup
});
最佳答案
在状态中存储一个不会被自动选择的虚假初始视频索引(空,未定义)。创建一个接受视频索引作为参数的点击处理程序,然后将其设置为状态。在渲染函数中,使用您拥有 this.state.videoIndex
的事实来测试它是否等于当前正在渲染的视频 div 并相应地设置其属性。
constructor(props) {
super(props);
this.state = {
videoIndex: null, // falsey value
}
}
videoClickHandler = index => this.setState(prevState => ({ videoIndex: prevState.videoIndex ? null : index})); // if truthy videoIndex, set null, else, set index
this.props.Videos.map((video, index) => {
return (
<div onClick={() => this.videoClickHandler(index)}> // pass index to callback
...
<div style={{display: this.state.videoIndex === index ? "block" : "none"}}> // test if state value equals current index
...
</div>
);
})) : null
关于javascript - 如何在 React 中循环弹出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54003932/