组件使用记录(持续更新)
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>
)
}