@ahwui/count-down
Version:
ui component
50 lines • 1.51 kB
JavaScript
import _extends from "@babel/runtime/helpers/extends";
import _objectWithoutPropertiesLoose from "@babel/runtime/helpers/objectWithoutPropertiesLoose";
var _excluded = ["seconds", "isRun", "text", "extraText", "onStart", "onChange"];
import React, { useRef, useState, useEffect } from 'react';
import { jsx as _jsx } from "react/jsx-runtime";
import { jsxs as _jsxs } from "react/jsx-runtime";
var CountDown = props => {
var {
seconds = 60,
isRun = false,
text = '获取倒计时',
extraText = 's',
onStart,
onChange
} = props,
other = _objectWithoutPropertiesLoose(props, _excluded);
var counRef = useRef(seconds);
var [count, setCount] = useState(0);
var timer = undefined;
useEffect(() => {
isRun && run();
}, [isRun]);
var run = () => {
counRef.current = seconds;
setCount(seconds);
if (timer) {
clearInterval(timer);
}
onChange == null ? void 0 : onChange();
timer = setInterval(() => {
counRef.current--;
setCount(counRef.current);
if (counRef.current === 0) {
clearInterval(timer);
timer = undefined;
onChange == null ? void 0 : onChange(true);
}
}, 1000);
};
if (!isRun) {
return /*#__PURE__*/_jsx("span", _extends({}, other, {
onClick: () => onStart == null ? void 0 : onStart(),
children: text
}));
}
return /*#__PURE__*/_jsxs("span", _extends({}, other, {
children: [count, extraText]
}));
};
export default CountDown;