问题
我想在每次点击“Enter”时都能获取更新后的钩子状态值value
,但我总是得到初始值,而不是更新后的值。
代码
import React, { useState } from "react";
import ReactDOM from "react-dom";
import ContentEditable from "react-contenteditable";
const ItemCol = props => {
const [value, setValue] = useState("Initial Value");
const onChange = event => {
setValue(event.target.value);
console.log("onChange: " + value);
};
const keyDown = event => {
if (event.keyCode === 13) {
event.preventDefault();
//Value should be changed, but did not change
console.log("Enter Pressed: " + value);
}
};
return (
<ContentEditable
html={value}
onKeyDown={React.useCallback(keyDown)}
onChange={React.useCallback(onChange)}
/>
);
};
const rootElement = document.getElementById("root");
ReactDOM.render(<ItemCol />, rootElement);
CodeSandBox.io: https://codesandbox.io/embed/pensive-worker-31l3r
注意:keyCode 13 是 Enter 键。
注意2:我正在使用 react-contenteditable 依赖项。 (https://www.npmjs.com/package/react-contenteditable)
请帮我解决这个问题,我已经为此烦恼了几个小时。谢谢!