I want to get the value of the latest value defined above in the keydownListener method, but I find that each time I get the initial value. Which great god has visited this question on one page? please answer it. I would appreciate it.
function Input(props) {
let inputRef = useRef(null);
let { value, handleChange, handleKeyDown, handleBlur, handleFocus } = useInputValue(inputRef,props.addTodo);
return (
<input
ref={inputRef}
className={styles["input"]}
value={value}
onFocus={handleFocus}
onBlur={handleBlur}
// onKeyDown={handleKeyDown}
onChange={handleChange}
placeholder={"What needs to be done?"}
/>
)
export const useInputValue = (inputRef,addTodo) => {
let [value, setValue] = useState("");
let focusStatus = useRef(false);
const handleChange = useCallback((e) => {
let v = e.target.value;
setValue(v);
}, [])
const handleFocus = () => {
focusStatus.current = true;
inputRef.current.addEventListener("keydown", keydownListener);
}
const handleBlur = () => {
focusStatus.current = false;
inputRef.current.removeEventListener("keydown", keydownListener);
}
const keydownListener = (e) => {
if (e.keyCode === 13 && focusStatus.current) {
addTodo(value); //""
setValue("");
}
}
return { value, handleChange, handleBlur, handleFocus }