vtils
Version:
一个面向业务的 JavaScript/TypeScript 实用程序库。
42 lines • 1.56 kB
JavaScript
import { useCallback, useState } from 'react';
import { useLatest, useUpdateEffect } from 'react-use';
/**
* 受控值。
*
* @param props 组件的属性
* @param options 选项
*/
export function useControllableValue(props, options) {
var latestProps = useLatest(props);
var latestOptions = useLatest(options);
var getInitialValue = useCallback(function () {
if (latestOptions.current.valuePropName in latestProps.current) {
return latestProps.current[latestOptions.current.valuePropName];
}
if (latestOptions.current.defaultValuePropName in latestProps.current) {
return latestProps.current[latestOptions.current.defaultValuePropName];
}
return latestOptions.current.defaultValue;
}, []);
var _useState = useState(getInitialValue),
value = _useState[0],
setValue = _useState[1];
useUpdateEffect(function () {
if (options.valuePropName in props) {
setValue(props[options.valuePropName]);
}
}, [props[options.valuePropName]]);
var handleSetValue = useCallback(function (nextValue) {
if (!(latestOptions.current.valuePropName in latestProps.current) || latestOptions.current.alwaysUpdateValue) {
setValue(nextValue);
}
if (typeof latestProps.current[latestOptions.current.callbackPropName] === 'function') {
;
latestProps.current[latestOptions.current.callbackPropName](nextValue);
}
}, []);
var handleResetValue = useCallback(function () {
handleSetValue(getInitialValue());
}, []);
return [value, handleSetValue, handleResetValue];
}