Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/21.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Html 输入类型编号不更新输入时的值_Html_Reactjs_Typescript - Fatal编程技术网

Html 输入类型编号不更新输入时的值

Html 输入类型编号不更新输入时的值,html,reactjs,typescript,Html,Reactjs,Typescript,应用程序保存一个输入元素,该元素在回车、模糊和单击下一步按钮时更新。当我在dev tools中检查元素时,value属性在blur和next按钮单击时都会更新,但在enter上不会更新 import * as React from "react"; import { render } from "react-dom"; interface IAppProps { InputVal: number; onEnter: (num: number) => void; } const

应用程序保存一个输入元素,该元素在回车、模糊和单击下一步按钮时更新。当我在dev tools中检查元素时,value属性在blur和next按钮单击时都会更新,但在enter上不会更新

import * as React from "react";
import { render } from "react-dom";

interface IAppProps {
  InputVal: number;
  onEnter: (num: number) => void;
}

const Parent: React.FC = () => {
  const [currentValue, setCurrentValue] = React.useState(1);
  const grabVal = (val: number) => {
    console.log("New value::", val);
    setCurrentValue(val);
  };

  return <App InputVal={currentValue} onEnter={grabVal} />;
};

const App: React.FC<IAppProps> = ({ InputVal, onEnter }) => {
  const inputRef: any = React.createRef();
  const handleEnterKey = (e: any) => {
    if (e.keyCode === 13) {
      onEnter(Number((e.target as HTMLInputElement).value));
    }
  };

  const nextClick = (e: any) => {
    inputRef.current.value = InputVal + 1;
    onEnter(InputVal + 1);
  };

  const blurry = (e: any) => {
    onEnter(Number(e.target.value));
  };

  return (
    <>
      <input
        type="number"
        onKeyUp={handleEnterKey}
        ref={inputRef}
        defaultValue={InputVal as any}
        onBlur={blurry}
      />
      <button onClick={nextClick}>Next</button>
    </>
  );
};

render(<Parent />, document.getElementById("root"));
我怎样才能让它在回车时更新


工作演示:

您想更新什么

这段代码在理论上是按它应该的方式工作的,但是当您执行keyup调用时,在事件处理程序中,您所做的只是控制台记录值并将其设置为新状态

现在在下一个方法调用中增加数字的唯一方法

 <input
        type="number"
        onKeyUp={handleEnterKey}
        ref={inputRef}
        defaultValue={InputVal as any}
        onBlur={blurry}
        value={InputVal as number}
      />

我想看到value属性在enter上更新,在Blur和next button click上更新的方式。onBlur除了在父级中触发console.log之外,什么都不做。button click更新子级中的UI的唯一原因是您在第30行明确设置了值,删除inputRef.current.value=InputVal+1;用户界面也不会更新。查看输入元素的值属性使用您的代码,您无法在字段中键入任何内容。请参见我的模糊函数,其操作与handleEnterKey相同,但当模糊触发时,它实际上会更新输入的值属性。只需检查dev工具中的元素。对于HandleEnterkey,它不会这样做。我很确定问题的原因是使用了defaultValue vs value。