React Hooks-useState值不能更改

时间:2019-06-04 06:44:32

标签: reactjs contenteditable react-hooks

问题

每当我单击输入时,我都希望获得更新的挂钩状态的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

请帮助我,因为我这个问题持续了几个小时。谢谢!

2 个答案:

答案 0 :(得分:3)

ContentEditable组件似乎可以记住onKeydown方法,因此,无论何时调用它,它都会从其初始闭包中打印出值,这就是为什么始终具有初始值的原因。

要解决此关闭问题,您可以将值保留在ref中并对其进行变异

const ItemCol = props => {
  const [value, setValue] = useState("Initial Value");
  const valRef = useRef(value);
  const onChange = event => {
    setValue(event.target.value);
    valRef.current = event.target.value;
  };

  const keyDown = event => {
    if (event.keyCode === 13) {
      event.preventDefault();
      //Value should be changed, but did not change
      console.log("Enter Pressed: " + valRef.current);
    }
  };

  return (
    <ContentEditable
      html={value}
      onKeyDown={keyDown}
      onChange={React.useCallback(onChange)}
    />
  );
};

Working demo

答案 1 :(得分:0)

@Michael Harley,问题出在关闭或在react-content-editable中设置react-content-editable onkeydown函数设置的方式。

工作演示:-https://codesandbox.io/embed/elated-bohr-jeu4u?fontsize=14

资源:-https://overreacted.io/a-complete-guide-to-useeffect/