[英]Passing refs for carousel into typescript using React and Ant design?
我正在尝试使用 React + Ant Design 实现按钮来滚动轮播。
我已经使用 React refs 成功地通过单个轮播实现了它。
我想让按钮滚动两个轮播。 所以我将滚动功能nextPane
和prevPane
到名为LandingPage
的父 class 中。 这里我还为每个轮播构造了两个React.createRef
并将它们传递到相应的组件中。
登陆页面.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
如何将参考正确传递和操作到两个轮播组件中?
React.createRef()
的类型是什么? 我正在使用any
我认为不正确的当前。
您需要将 refs 转发到Carousel
组件。 这对于功能组件来说要简单得多,因为对于基于类的组件,您需要制作一个包装器 function 来为您转发它们,就像文档中的最后一个示例一样,因为 class 组件不接收参考道具:
class ImageCarousel extends Component<Props, State> {
...
}
const ForwardWrapper = (props, ref) => {
return <ImageCarousel {...props} ref={ref} />;
}
const CarouselWithRef = React.forwardRef(ForwardWrapper);
然后你可以像使用普通组件一样使用它:
<CarouselWithRef {...props} ref={this.imageCarousel}/>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.