组件使用记录(持续更新)
1、Input 组件自动获得焦点
和普通的 input 标签不同,antd 已经给 Input 组件提供了 InputRef 类型。在 Input 组件上添加 ref ,获取到的是 InputRef 类型的值,而不是 HTMLInputElement 类型的值。
1.1 InputRef 类型
interface InputRef {
focus: (options?: InputFocusOptions) => void;
blur: () => void;
setSelectionRange: (start: number, end: number, direction?: 'forward' | 'backward' | 'none') => void;
select: () => void;
input: HTMLInputElement | null;
}
1.2 代码实现
import React, { useRef } from 'react';
import { Input, Button } from 'antd';
import type { InputRef } from 'antd';
const Test = () => {
const inputRef = useRef<InputRef>(null);
const inputFocus = () => {
if (inputRef.current) inputRef.current.focus();
}
return (
<div>
<Input ref={inputRef} />
<Button onClick={inputFocus}>获取焦点<Button>
</div>
)
}
2、Carousel 组件 走马灯垂直切换
2.1 增加 vertical 属性
import type { CarouselRef } from 'antd/es/carousel'
const LoginMain = () => {
const carouselRef = useRef<CarouselRef>(null);
return (
<Carousel
ref={carouselRef}
autoplay
vertical
// 其他属性
>
// 其他...
</Carousel>
)
}
2.2 CarouselRef 类型
interface CarouselRef {
goTo: (slide: number, dontAnimate?: boolean) => void;
next: () => void;
prev: () => void;
autoPlay: (palyType?: 'update' | 'leave' | 'blur') => void;
innerSlider: any;
}