我想访问handleKeyDown
函数中value
状态变量的值。但是,当我继续打字时,我注意到value
没有设置为最新的输入值,而是设置为以前的输入状态。我使用setTimeout
,这样handleChange
将首先被调用,setValue()
函数将改变value
的值。修改后的值会反映在handleKeyDown
函数里面。
import "./styles.css";
import { useState } from "react";
export default function App() {
const [value, setValue] = useState("");
const handleChange = (e) => {
console.log("called handle changed");
setValue(e.target.value);
};
const handleKeyDown = (e) => {
console.log("called keydown");
console.log(value);
};
return (
<div className="App">
<input
value={value}
onChange={handleChange}
onKeyDown={(e) => setTimeout(() => handleKeyDown(e), 0)}
/>
</div>
);
}
e.target.value
显示最新的和必需的值,但value
本身显示旧的值。如何等待handleChange
使用setValue
设置值,handleKeyDown
使用value
?
可以使用useRef钩子获取当前值
import "./styles.css";
import { useState, useRef } from "react";
export default function App() {
const [value, setValue] = useState("");
const updatedValue = useRef("");
const handleChange = (e) => {
console.log("called handle changed");
setValue(e.target.value);
updatedValue.current = e.target.value;
};
const handleKeyDown = (e) => {
console.log("called keydown");
console.log(updatedValue.current);
};
return (
<div className="App">
<input
value={value}
onChange={handleChange}
onKeyDown={(e) => setTimeout(() => handleKeyDown(e), 0)}
/>
</div>
);
}