固定在提交而不是on Change上
我有一个表格,在其中使用输入字段的输入发送到后端。
例如,我有一个看起来像这样的变量:
const [data, setData] = useState([])
const [inputField, setInputField] = useState()
然后我有一个form
,看起来像这样:
<form onSubmit={fetchData}>
<input type="number" value={value} onChange={(e) => setInputField(e.target.value)} />
<button type="submit">Fetch data</button>
</form>
fetchdata
给出:
function fetchData(e?: any) {
e?.preventDefault();
POST("/api", {
inputField: inputField,
}).then(async (response) => {
const json = await response.json();
setData({
retrievedData: json.retrievedData,
});
});
}
我也有其他表单如果此onChange
更新很好,但是对于某些输入字段,我不需要它在单击触发表单的实际提交按钮之前进行更新/重新渲染。
那么,当单击按钮时,如何更新InputField
的状态,而不是每次在输入字段中编写新字符时更新的位置?
I have a form, where I use the input from the input fields to send to a back-end.
For example, I have a variable looking something like this:
const [data, setData] = useState([])
const [inputField, setInputField] = useState()
Then I have a form
that looks something like this:
<form onSubmit={fetchData}>
<input type="number" value={value} onChange={(e) => setInputField(e.target.value)} />
<button type="submit">Fetch data</button>
</form>
The fetchData
is given by:
function fetchData(e?: any) {
e?.preventDefault();
POST("/api", {
inputField: inputField,
}).then(async (response) => {
const json = await response.json();
setData({
retrievedData: json.retrievedData,
});
});
}
I have other forms as well, where this onChange
updating is good, but for some input fields I don't need it do update/re-render before the actual submit button that triggers the form are clicked.
So how do I update the state of the inputField
when the button is clicked, instead of now where it updates every time I write a new character in the input field ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
尝试一下
Try this
您可以为此使用
useref
挂钩。然后按按钮单击您可以得到这样的值
You can use
useRef
hook for that.Then on button click you can get the value like that
您不需要这个状态,甚至不需要裁判。您可以直接从提交事件(
event.target。您将需要将
name
属性添加到&lt; input/&gt;
以使其可以从事件目标访问。请在下面找到示例:You don't need a state for that and you don't even need a ref. You can get the form values directly from the submit event (
event.target.<input name>.value
). You will need to add thename
property to the<input />
to make it accessible from the event target. Please, find the example below: