@tencentcloud/call-uikit-react
Version:
An Open-source Voice & Video Calling UI Component Based on Tencent Cloud Service.
32 lines (26 loc) • 709 B
text/typescript
import { useState } from 'react';
import { noop } from '../util';
interface IUseControlledProps<R, K> {
props: R
key: K;
onChange?: (e?: any) => any;
defaultOptions?: any
}
export default function useControlled<R extends object, K extends keyof R>({
props, key, onChange, defaultOptions,
}: IUseControlledProps<R, K>) {
const controlled = Reflect.has(props, key);
const value = props[key];
const defaultValue = defaultOptions[key];
if (controlled) {
return [value, onChange || noop];
}
const [internalValue, setInternalValue] = useState(defaultValue);
return [
internalValue,
(newValue) => {
setInternalValue(newValue);
onChange?.(newValue);
},
];
}