我的应用程序将 react-images 用于灯箱,将 react-carousel-images 用于轮播。我的 api 有一个标题和图像。我遇到的问题是页脚标题中的标题始终作为所选图像出现,并且在灯箱轮播中不会改变。我认为这与所选图像的索引有关?到目前为止,我的代码是:问题示例: https ://codesandbox.io/s/react-multi-corousal-issue-72s9o?file=/src/Slider.js滑块.jsimport React, { Component } from "react";// import "../slider/slider.css";import "./slider.css";import Carousel from "react-multi-carousel";import "react-multi-carousel/lib/styles.css";import LightBox, { Modal, ModalGateway } from "react-images";const responsive = { superLargeDesktop: { breakpoint: { max: 4000, min: 3000 }, items: 1 }, desktop: { breakpoint: { max: 3000, min: 1024 }, items: 1 }, tablet: { breakpoint: { max: 1024, min: 464 }, items: 1 }, mobile: { breakpoint: { max: 464, min: 0 }, items: 1 }};class Slider extends Component { _isMounted = false; state = { awsApiData: [], loading: false, //selectedIndex: 0, selectedImage: {}, lightboxIsOpen: false }; componentDidMount() { this._isMounted = true; console.log("app mounted"); this.setState({ loading: true }); /*global fetch */ fetch("https://onelbip0e6.execute-api.eu-west-2.amazonaws.com/livestage/imgApi") .then(data => data.json()) .then(data => // this.setState({ awsApiData: data[0], loading: false }, () => this.setState( { // awsApiData: data.map(item => ({source: item.download_url })), awsApiData: data.map(item => ({ ...item, source: item.image })), loading: false }, () => console.log(data) ) ); } componentWillUnmount() { this._isMounted = false; } toggleLightbox = (post, selectedIndex) => { // this.setState(state => ({ // lightboxIsOpen: !state.lightboxIsOpen, // selectedIndex // })); this.setState(state => ({ lightboxIsOpen: !state.lightboxIsOpen, selectedImage: { title: post.title, index: selectedIndex } })); };
1 回答
撒科打诨
TA贡献1934条经验 获得超2个赞
您的标题设置为,但当您的灯箱视图更改时this.state.selectedImage.title,您永远不会更新状态(即 call )。setState()
您需要将onViewChange处理程序添加到LightBox组件:
<LightBox onViewChange={handleLightBoxViewChange} .../>
该处理程序也将接收视图更改的项目的索引。handleLightBoxViewChange呼吁setState更新selectedImage:_
handleLightBoxViewChange = (newIndex) => {
this.setState(state => ({
selectedImage: state.awsApiData[newIndex]
}));
};
如果您不想更新状态,您的页脚组件会接收当前视图,因此您可以像这样更新它:
<LightBox
components={{
FooterCaption: ({currentView}) => <div>{currentView.title}</div>
}}
//...
/>
添加回答
举报
0/150
提交
取消