主要用于: Input Select Radio Switch 等
import { useState, useCallback } from 'react';
/** 默认为 value */
type EventValueType<T = any> = 'value' | 'checked' | ((evt: T) => void) | boolean;
function getValueByType(evt: any, type?: EventValueType) {
/** 适用于: Input Checkbox */
if (type === 'value' || type === 'checked') {
return evt.target[type];
}
/** Switch */
if (typeof type === 'boolean') {
return type ? evt.target.value : evt;
}
if (typeof type === 'function') {
return type(evt);
}
/** Tabs Select */
return evt;
}
const useChange = <T, E = any>(defaultValue?: T, type?: EventValueType<E>) => {
const [value, setValue] = useState(defaultValue);
const onChange = useCallback(
(evt) => {
const val = getValueByType(evt, type);
setValue(val);
},
[value],
);
const reset = useCallback(() => {
setValue(defaultValue);
}, [defaultValue]);
return [value as T, onChange, { reset, setValue }] as const;
};
export default useChange;