首页 > 解决方案 > 如何在 react-countdown 中调用 onStart 函数?

问题描述

<Countdown
    date={Date.now() + (n.duration)}
    ref={this.refCallback}
    autoStart={false}

    renderer={({ hours, minutes, seconds, completed }) => {
        if (completed) {
            // Render a completed state
            return <div>Times up</div>;
        } else {
            // Render a countdown
            return <h1 className="m-0 font-weight-bold">{hours}:{minutes}:{seconds}</h1>;
        }
    }}
/>

这是文档 https://www.npmjs.com/package/react-countdown

谢谢。

标签: reactjscountdown

解决方案


您可以查看库 CountDown 组件的文档 api。它提供了方法 start here。您可以调用this.refCallback.start()一些从哪里开始。例子:

const Component =(props) => {
    const ref= useRef();

    const handleStart = (e) => {
        ref.current?.start();
    }

    const handlePause = (e) => {
        ref.current?.pause();
    }

    return <>
        <button onClick={handleStart}> Start </button>
        <button onClick={handlePause}> Pause </button>
        <Countdown
            date={Date.now() + (20000)}
            ref={ref}
            autoStart={false}

            renderer={({ hours, minutes, seconds, completed }) => {
                if (completed) {
                    // Render a completed state
                    return <div>Times up</div>;
                } else {
                    // Render a countdown
                    return <h1 className="m-0 font-weight-bold">{hours}:{minutes}:{seconds}</h1>;
                }
            }}
        />
        </>
}

推荐阅读