由于某种原因,showNumber 变量在提交点击时会更新,但不会在
返回语句中更新。无论如何,有没有更好的方法来写这个?请记住,在
每次输入 on Change 时,不应简单地更改行,而应仅在单击提交按钮后更改。我想一种解决方案是通过 refs 选择输入,但我希望有更好的方法。请帮忙。
function App() {
const [number, setNumber] = useState(1);
let showNumber = 0;
const rerender = () => {
showNumber = number;
}
const handleChange = (e) => { setNumber(e.target.value) }
return (
<header>
<input type='number' onChange={handleChange} />
<button type='submit' onClick={rerender}>submit</button>
<p>the number is {showNumber}</p>
</header>
);
}
export default App;
通过包装表单标签,您可以实现,因此当您单击仅提交时,它将获得表单值,您可以使用 name 属性获取值
示例代码
import React, { useState, useEffect } from "react";
import ReactDOM from "react-dom";
function App() {
const [number, setNumber] = useState(1);
const rerender = e => {
e.preventDefault();
const data = new FormData(e.target);
setNumber(data.get("number"));
};
return (
<header>
<form onSubmit={rerender}>
<input type="number" name="number" />
<button>Submit</button>
</form>
<p>the number is {number}</p>
</header>
);
}
export default App;
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
工作代码沙箱