import cns from 'classnames' import React, { ChangeEvent, HTMLAttributes, InputHTMLAttributes, ReactNode, Ref, useCallback, useRef } from 'react' import { CloseCircleIcon } from '../icons' import { useLangData, usePrefix } from '../ConfigProvider' import { concat } from '../utils' import { useFocused, useRefs, useValue } from '../utils/hooks' import { CommonProps, useInputStyle } from './input' import { WithRef } from '../utils/type' export interface Props extends CommonProps { /** 是否有清空功能 */ clearable?: boolean /** 前缀 */ prefix?: ReactNode /** 后缀 */ suffix?: ReactNode /** * 获取 input 引用 * * @deprecated use inputProps.ref instead */ inputRef?: Ref /** 需要传给 `input` 的属性 */ inputProps?: WithRef, HTMLInputElement> /** 根元素的 html 属性 */ rootHtmlProps?: WithRef, HTMLDivElement> } export default function TextInput({ value: valueFromProps, defaultValue = '', onChange, placeholder, disabled = false, size, validateStatus, clearable = false, prefix, suffix, inputRef: inputRefFromProps, inputProps, rootHtmlProps, className, style }: Props) { const inputClassName = usePrefix('text-input') const { focused, focusedHandlers } = useFocused(inputProps, disabled) const innerInputRef = useRef(null) const inputRef = useRefs(inputRefFromProps, innerInputRef, inputProps?.ref) const { value, setValue } = useValue({ valueFromProps, defaultValue, onChange }) const inputStyleClassName = useInputStyle({ focused, validateStatus, size, disabled }) const classname = cns( inputStyleClassName, inputClassName, className, rootHtmlProps?.className ) const prefixView = prefix != null && (
{prefix}
) const handleClear = useCallback(() => { setValue('') innerInputRef.current?.focus() }, [setValue]) const { clearText } = useLangData('textInput') const clearIconView = !disabled && clearable && value && ( ) const hasSuffix = suffix != null || clearIconView const suffixView = hasSuffix && (
{clearIconView} {suffix}
) const handleChange = useCallback((e: ChangeEvent) => { inputProps?.onChange?.(e) setValue(e.target.value) }, [inputProps, setValue]) const handleWrapperClick = useCallback((e: React.MouseEvent) => { rootHtmlProps?.onClick?.(e) innerInputRef.current?.focus() }, [rootHtmlProps]) return (
{prefixView} {suffixView}
) }