所以我有一个钩子,可以在更改时获取输入字段的值并设置变量。
更新
HooksLib.js
import { useState } from "react";
export function useFormFields(initialState) {
const [fields, setValues] = useState(initialState);
return [
fields,
function(e, name = '') {
if (e instanceof Object && e.target instanceof Object) {
// Safe to assume it was an event passed in
setValues({ ...fields, [e.target.id]: e.target.value });
} else {
// Assume the value was passed in directly
setValues({ ...fields, [name]: e });
}
}
];
}
我想使用相同的钩子在函数调用中设置变量。我将如何处理?
如何将event.target.id和event.target.value添加到函数调用中?
我要添加到的功能在下面。...特别是///then update a variable called "fields.customerId" as the value of "customer"
所在的位置。
handleSignUpSubmit异步功能
const [fields, handleFieldChange] = useFormFields({
name: "",
email: "",
customerId: "null"
});
async function handleSignUpSubmit(event) {
event.preventDefault();
setIsLoading(true);
try {
const customer = await createCustomer({ email: fields.email, name: fields.name});
///then update a variable called "fields.customerId" as the value of "customer"
} catch (e) {
alert(e.message);
setIsLoading(false);
}
}
感谢您的帮助!
答案 0 :(得分:2)
如果我正确理解了您的问题,则会看到两个选择。
您可以创建一个类似于事件的对象并将其传递给:
const myEvent = {
target: {
id: 'test',
value: 'test2'
}
}
...
handleFieldChange(myEvent);
或者另一种方法是在自定义钩子中包括一个检查,以允许将事件或纯值作为键名作为可选参数传入:
function(e, name = '') {
if (e instanceof Object && e.target instanceof Object) {
// Safe to assume it was an event passed in
setValues({ ...fields, [e.target.id]: e.target.value });
} else {
// Assume the value was passed in directly
setValues({ ...fields, [name]: e });
}
}
然后这样称呼它:
const customer = await createCustomer({ email: fields.email, name: fields.name});
handleFieldChange(customer, 'customerId');