【发布时间】:2019-06-03 10:42:27
【问题描述】:
App 包含一个输入元素,该元素在输入、模糊和下一个按钮单击时更新。当我在开发工具中检查元素时,value 属性会在模糊和下一步按钮单击时更新,但不会在输入时更新。
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"));
如何在输入点击时更新它?
【问题讨论】:
标签: html reactjs typescript