gpt4 book ai didi

javascript - 在 Typescript 中使用 Ant Design 的轮播下一个和上一个 Pane 方法?

转载 作者:行者123 更新时间:2023-12-02 22:44:18 25 4
gpt4 key购买 nike

我使用 Ant Design 作为我的应用程序的设计框架。该框架有一个 Carousel组件,该组件公开了两种方法来切换轮播中的 Pane 。

这是在 Javascript 中使用它的示例.

这是我使用 Typescript 的尝试:

interface State {
slider: ReactNode;
}

interface Props {}

class ImageCarousel extends Component<Props, State> {
private carousel: any;

constructor(props: Props) {
super(props);
this.carousel = React.createRef();
}

nextPane() {
this.carousel.next();
}
prevPane() {
this.carousel.prev();
}

render() {
return (
<CarouselWrapper>
<RegularButtonWrapper>
<RegularButton
size="large"
icon="caret-left"
onClick={this.prevPane}
/>
</RegularButtonWrapper>
<FlexCarousel>
<Carousel
ref={node => (this.carousel = node)}
speed={700}
effect="fade"
autoplay
autoplaySpeed={3000}
>
<img src={IU} />
<img src={IU2} />
<img src={IU3} />
<img src={IU4} />
<img src={IU5} />
</Carousel>
</FlexCarousel>
<RegularButtonWrapper>
<RegularButton
size="large"
icon="caret-right"
onClick={this.nextPane}
/>
</RegularButtonWrapper>
</CarouselWrapper>
);
}
}

export default ImageCarousel;

上面的方法不起作用 - TypeError: 无法读取未定义的属性“carousel”

如何将这些方法与 Typescript 结合使用?

最佳答案

您需要通过访问 ref 存储它的 current 属性来访问 DOM 节点本身的导航方法。这是一个基本示例。您收到该错误是因为您在前一个/下一个方法中使用了 this ,因此它实际上指的是函数作用域。尝试将它们转换为箭头函数,如下所示(按照其他答案中提到的方式绑定(bind)构造函数中的方法也可以)。

class App extends React.Component {
constructor(props) {
super(props);
this.carouselRef = createRef();
}

onChange = (a, b, c) => {
console.log(a, b, c);
};

handleNext = () => this.carouselRef.current.next();

handlePrev = () => this.carouselRef.current.prev();

render() {
return (
<div className="App">
<Carousel afterChange={this.onChange} ref={this.carouselRef}>
<div>
<h3>1</h3>
</div>
<div>
<h3>2</h3>
</div>
<div>
<h3>3</h3>
</div>
<div>
<h3>4</h3>
</div>
</Carousel>
<Button onClick={this.handlePrev}>Previous</Button>
<Button onClick={this.handleNext}>Next</Button>
</div>
);
}
}

Sanbox here .

关于javascript - 在 Typescript 中使用 Ant Design 的轮播下一个和上一个 Pane 方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58475891/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com