和旋转木马从类组件转换为功能



我有以下代码

class Gallery extends Component {
state = {
media: null,
nav: null
};
componentDidMount = () => {
this.setState({
media: this.media,
nav: this.nav
});
};
render() {
return (
<>
<Carousel
asNavFor={this.state.nav}
touchMove={true}
dots={false}
ref={(carousel) => {
this.media = carousel;
}}
>
<div>
<h3>1</h3>
</div>
<div>
<h3>2</h3>
</div>
<div>
<h3>3</h3>
</div>
</Carousel>
<Carousel
slidesToShow={2}
asNavFor={this.state.media}
ref={(carousel) => (this.nav = carousel)}
>
<div>
<h3>1</h3>
</div>
<div>
<h3>2</h3>
</div>
<div>
<h3>3</h3>
</div>
</Carousel>
</>
);
}
} 

是基于类组件编写的,请帮我转换成功能组件

我试过这样,但它不能正常工作。当我们改变缩略图图库时,主图库没有改变。如果我将缩略图或按钮从1更改为2,则主幻灯片也应从1更改为2。但是它没有改变

const Gallery = () => {
const [media, setMedia] = useState(null);
const [nav, setNav] = useState(null);
const carousel = useRef(null);
const handleNext = () => {
carousel.current.next();
};
const handlePrev = () => carousel.current.prev();
useEffect(() => {
setMedia(null);
setNav(null);
}, [media, nav]);
return (
<>
<Carousel asNavFor={nav} touchMove={false} dots={false} ref= 
{carousel}>
<div>
<h3>1</h3>
</div>
<div>
<h3>2</h3>
</div>
<div>
<h3>3</h3>
</div>
</Carousel>
<Button onClick={handlePrev}> prev </Button>
<Button onClick={handleNext}> next </Button>
<Carousel
slidesToShow={2}
asNavFor={media}
ref={carousel}
>
<div>
<h3>1</h3>
</div>
<div>
<h3>2</h3>
</div>
<div>
<h3>3</h3>
</div>
</Carousel>
</>
);
};

请帮我解决这个问题,谢谢:)

我已经更新了这个链接,或者你也可以看到下面的代码

import React, { Component, useState } from "react";
import ReactDOM from "react-dom";
import "antd/dist/antd.css";
import "./index.css";
import { Carousel } from "antd";
const Gallery = () => {
const mediaRef = React.useRef(null);
const navRef = React.useRef(null);
const onChange = (currentSlide) => {
console.log(currentSlide);
mediaRef.current.goTo(currentSlide, false);
};
return (
<div>
<Carousel
asNavFor={navRef.current}
touchMove={false}
dots={false}
ref={mediaRef}
>
<div>
<h3>1</h3>
</div>
<div>
<h3>2</h3>
</div>
<div>
<h3>3</h3>
</div>
<div>
<h3>4</h3>
</div>
</Carousel>
<Carousel
slidesToShow={3}
centerMode={true}
asNavFor={mediaRef.current}
draggable={true}
ref={(carousel) => (navRef.current = carousel)}
afterChange={onChange}
swipeToSlide={true}
touchThreshold={50}
focusOnSelect={true}
>
<div>
<h3>1</h3>
</div>
<div>
<h3>2</h3>
</div>
<div>
<h3>3</h3>
</div>
<div>
<h3>4</h3>
</div>
</Carousel>
</div>
);
};
ReactDOM.render(<Gallery />, document.getElementById("container"));

相关内容

  • 没有找到相关文章

最新更新