ขนาดวิดีโอ: 1280 X 720853 X 480640 X 360
แสดงแผงควบคุมโปรแกรมเล่น
เล่นอัตโนมัติ
เล่นใหม่
import React, { useEffect, useRef, useState } from "react";const InputWithTimer = ({ initialTime = 30 }) => { const [time, setTime] = useState(initialTime); // Timer value const [inputValue, setInputValue] = useState(""); // User input const inputRef = useRef(null); // Reference to the input field // Timer logic useEffect(() => { const timer = setInterval(() => { setTime((prevTime) => (prevTime > 0 ? prevTime - 1 : 0)); // Countdown }, 1000); return () => clearInterval(timer); // Cleanup on unmount }, []); // Focus on the input field when the component mounts useEffect(() => { if (inputRef.current) { inputRef.current.focus(); } }, []); // Handle input changes const handleInputChange = (e) => { setInputValue(e.target.value); }; // Handle resend button click const handleResend = () => { setTime(initialTime); // Reset timer setInputValue(""); // Clear input if (inputRef.current) { inputRef.current.focus(); // Focus back on input } }; return ( {time > 0 ? ( Time Remaining: {time}s ) : ( Resend )} );};export default InputWithTimer;
import React, { useEffect, useRef, useState } from "react";
const InputWithTimer = ({ initialTime = 30 }) => {
const [time, setTime] = useState(initialTime); // Timer value
const [inputValue, setInputValue] = useState(""); // User input
const inputRef = useRef(null); // Reference to the input field
// Timer logic
useEffect(() => {
const timer = setInterval(() => {
setTime((prevTime) => (prevTime > 0 ? prevTime - 1 : 0)); // Countdown
}, 1000);
return () => clearInterval(timer); // Cleanup on unmount
}, []);
// Focus on the input field when the component mounts
useEffect(() => {
if (inputRef.current) {
inputRef.current.focus();
}
}, []);
// Handle input changes
const handleInputChange = (e) => {
setInputValue(e.target.value);
};
// Handle resend button click
const handleResend = () => {
setTime(initialTime); // Reset timer
setInputValue(""); // Clear input
if (inputRef.current) {
inputRef.current.focus(); // Focus back on input
}
};
return (
{time > 0 ? (
Time Remaining: {time}s
) : (
Resend
)}
);
};
export default InputWithTimer;