gaowei1012 / blog

this is blog
2 stars 0 forks source link

React Hooks写一个倒计时插件 #57

Open gaowei1012 opened 3 years ago

gaowei1012 commented 3 years ago

const [count, setCount] = useState(0)

useEffect(() => {
        return () => {
            clearInterval(intervalRef.current);
        };
    }, []);

    useEffect(() => {
        if (count === 59) {
          intervalRef.current = setInterval(() => {
            setCount((preCount) => preCount - 1);
          }, 1000);
        } else if (count === 0) {
          clearInterval(intervalRef.current);
        }
 }, [count]);
gaowei1012 commented 3 years ago
<TouchableOpacity
                        style={styles.sendCode}
                        activeOpacity={1}
                        onPress={handleSendCode}
                        disabled={disabled}>
                        <View style={styles.timerBox}>
                            <Text style={styles.timerText}>
                                {count ? `${count}秒后获取` : '获取验证码'}
                            </Text>
                        </View>
  </TouchableOpacity>
gaowei1012 commented 3 years ago

const handleSendCode =useCallback(() => {
    setCount(59);

}, [])