【发布时间】:2020-03-10 02:14:36
【问题描述】:
我正在尝试使用 React + Ant Design 实现按钮来滚动轮播。
我已经成功地通过使用 React refs 的单个轮播实现了它。
我想让按钮滚动两个轮播。所以我将滚动功能nextPane 和prevPane 提升到一个名为LandingPage 的父类中。这里我还为每个轮播构造了两个React.createRef,并传入对应的组件中。
LandingPage.tsx
class LandingPage extends Component<Props, State> {
// ToDo
private imageCarousel: any;
private textCarousel: any;
constructor(props: Props) {
super(props);
this.imageCarousel = React.createRef();
this.textCarousel = React.createRef();
}
nextPane = () => {
this.imageCarousel.next();
this.textCarousel.next();
};
prevPane = () => {
this.imageCarousel.prev();
this.textCarousel.prev();
};
render() {
return (
<Fragment>
<NavBar title="Athena."></NavBar>
<ImageCarouselWrapper>
<ImageCarousel
ref={this.imageCarousel}
nextPane={this.nextPane}
prevPane={this.prevPane}
/>
<WrapperCarouselOverlay>
<CarouselOverlay ref={this.textCarousel} />
</WrapperCarouselOverlay>
</ImageCarouselWrapper>
</Fragment>
);
}
}
ImageCarousel.tsx
interface State {}
interface Props {
ref: any;
nextPane: () => void;
prevPane: () => void;
}
class ImageCarousel extends Component<Props, State> {
private carousel: any;
constructor(props: Props) {
super(props);
this.carousel = React.createRef();
}
render() {
const { nextPane, prevPane, ref } = this.props;
return (
<CarouselWrapper>
<RegularButtonWrapper>
<RegularButton size="large" icon="caret-left" onClick={prevPane} />
</RegularButtonWrapper>
<FlexCarousel>
<Carousel
ref={ref} // This doesn't work, neither does 'node => ({ref} = node)'
speed={700}
effect="scrollx"
>
</img>
</Carousel>
</FlexCarousel>
<RegularButtonWrapper>
<RegularButton size="large" icon="caret-right" onClick={nextPane} />
</RegularButtonWrapper>
</CarouselWrapper>
);
}
}
我在传递 ref 时遇到错误,单击任何按钮都会产生:
TypeError: this.imageCarousel.next is not a function
如何将 ref 正确传递和操作到两个轮播组件中?
React.createRef()的类型是什么?我目前使用的是any,我认为这不正确。
【问题讨论】: