当前位置: 代码迷 >> 综合 >> Ant-design 源码分析之数据展示(五)Carousel
  详细解决方案

Ant-design 源码分析之数据展示(五)Carousel

热度:63   发布时间:2023-11-19 18:19:11.0

Ant-design 源码分析之数据展示(五)Carousel

2021SC@SDUSC

一、组件结构

1、ant代码结构
在这里插入图片描述
2、组件结构
antd中Carousel的index.tsx中引入了react-slick。

二、antd组件调用关系

1、index.tsx
导入相应模块以及相应的ICON图标

import * as React from 'react';
import SlickCarousel, {
     Settings } from '@ant-design/react-slick';
import classNames from 'classnames';
import {
     ConfigContext } from '../config-provider';

声明点位

//动画效果
export type CarouselEffect = 'scrollx' | 'fade';
//4个位置
export type DotPosition = 'top' | 'bottom' | 'left' | 'right';

定义CarouselProps接口。

// Carousel
export interface CarouselProps extends Omit<Settings, 'dots' | 'dotsClass'> {
    effect?: CarouselEffect;style?: React.CSSProperties;prefixCls?: string;slickGoTo?: number;dotPosition?: DotPosition;children?: React.ReactNode;dots?:| boolean| {
    className?: string;};
}

autoplay:是否自动切换,类型为boolean
dotPosition:面板指示点位置,可选top bottom left right,类型为string
dots:是否显示面板指示点,如果为 object 则同时可以指定 dotsClass,类型为boolean | { className?: string }
easing:动画效果,类型为string
effect:动画效果函数,类型为scrollx | fade
afterChange:切换面板的回调,类型为function(current)
beforeChange:切换面板的回调,类型为function(from, to)

export interface CarouselRef {
    goTo: (slide: number, dontAnimate?: boolean) => void;next: () => void;prev: () => void;autoPlay: boolean;innerSlider: any;
}

设置轮播参数

const Carousel = React.forwardRef<CarouselRef, CarouselProps>(({
     dots = true, arrows = false, draggable = false, dotPosition = 'bottom', ...props }, ref) => {
    const {
     getPrefixCls, direction } = React.useContext(ConfigContext);const slickRef = React.useRef<any>();
//切换到指定面板,dontAnimate为true不使用动画const goTo = (slide: number, dontAnimate = false) => {
    slickRef.current.slickGoTo(slide, dontAnimate);};
//实现自动轮播,切换界面React.useImperativeHandle(ref,() => ({
    goTo,autoPlay: slickRef.current.innerSlider.autoPlay,innerSlider: slickRef.current.innerSlider,prev: slickRef.current.slickPrev,next: slickRef.current.slickNext,}),[slickRef.current],);
    const prevCount = React.useRef(React.Children.count(props.children));
//动画效果React.useEffect(() => {
    if (prevCount.current !== React.Children.count(props.children)) {
    goTo(props.initialSlide || 0, false);prevCount.current = React.Children.count(props.children);}}, [props.children]);const newProps = {
    ...props,};
//渐显效果if (newProps.effect === 'fade') {
    newProps.fade = true;}
    const prefixCls = getPrefixCls('carousel', newProps.prefixCls);const dotsClass = 'slick-dots';newProps.vertical = dotPosition === 'left' || dotPosition === 'right';const enableDots = !!dots;const dsClass = classNames(dotsClass,`${
      dotsClass}-${
      dotPosition}`,typeof dots === 'boolean' ? false : dots?.className,);const className = classNames(prefixCls, {
    [`${
      prefixCls}-rtl`]: direction === 'rtl',[`${
      prefixCls}-vertical`]: newProps.vertical,});
  相关解决方案