@td-design/rn-hooks
Version:
从ahooks里面抽取的一些在rn项目里可以使用的hooks。提高开发效率
63 lines (59 loc) • 1.79 kB
JavaScript
;
var _tslib = require('../_virtual/_tslib.js');
var react = require('react');
var index$1 = require('../useMemoizedFn/index.js');
var index = require('../useSafeState/index.js');
/**
* 步进器效果
* @param initialValue
* @param options
* @returns
*/
function useCounter(initialValue, options) {
if (initialValue === void 0) { initialValue = 0; }
if (options === void 0) { options = {}; }
var _a = _tslib.__read(index(0), 2), current = _a[0], setCurrent = _a[1];
react.useEffect(function () {
setCurrent(getTargetValue(initialValue, options));
}, [initialValue, options]);
var setValue = function (value) {
setCurrent(function (c) {
var target = typeof value === 'number' ? value : value(c);
return getTargetValue(target, options);
});
};
var inc = function (delta) {
if (delta === void 0) { delta = 1; }
setValue(function (c) { return c + delta; });
};
var dec = function (delta) {
if (delta === void 0) { delta = 1; }
setValue(function (c) { return c - delta; });
};
var set = function (value) {
setValue(value);
};
var reset = function () {
setValue(initialValue);
};
var actions = {
inc: index$1(inc),
dec: index$1(dec),
set: index$1(set),
reset: index$1(reset),
};
return [current, actions];
}
function getTargetValue(val, options) {
if (options === void 0) { options = {}; }
var min = options.min, max = options.max;
var target = val;
if (typeof max === 'number') {
target = Math.min(max, target);
}
if (typeof min === 'number') {
target = Math.max(min, target);
}
return target;
}
module.exports = useCounter;