我正在使用useCallback
钩子构建表单onSubmit函数,这些钩子将在formik
中使用
我使用formik的组件可能看起来像这样
import { useContactForm } from './useContactForm'
//some functional component
const customSubmit = .... /some submit function
const { initialValues, handleSubmit } = useContactForm(customSubmit);
const formik = useFormik({
initialValues,
onSubmit: handleSubmit //something like this
});
return(
<form onSubmit ={formik.handleSubmit}>
<input
id="email"
name="email"
type="email"
onChange={formik.handleChange}
value={formik.values.email}
/>
<input
id="password"
name="password"
type="password"
onChange={formik.handleChange}
value={formik.values.password}
/>
<button type="submit">Submit</button>
</form>
)
和我的useContactForm.ts看起来像这样。 // useContactForm.ts
import { useCallback } from 'react';
interface IContactFormFields {
email: string,
password: string
}
type ISubmitFormType = (value: IContactFormFields, e?: React.FormEvent<HTMLFormElement>) => Promise<void>;
const useContactForm = (submitForm: ISubmitFormType) => {
const handleSubmit = useCallback(
( formFields : IContactFormFields ) => {
return submitForm(formFields).then(() => {
console.log('form submitted');
})
},[]);
const initialValues: IContactFormFields = {
email: "",
password: "",
};
return {
handleSubmit,
initialValues,
}
}
export default useContactForm;
我的问题useContactForm
应该获得自定义的提交函数名称submitForm
作为参数。
然后,我的ISubmitFormType
应该是什么样子?
答案 0 :(得分:1)
在这种情况下如何确定类型。
在您的示例中,submitForm的使用方式:
submitForm(formFields).then(() => {
console.log('form submitted');
})
是功能吗?:是
() => unknown
内容:formFields
(formFields) => unknown
返回的内容:Promise
(formFields) => Promise<unknown>
到目前为止我们所拥有的:
type ISubmitFormType = (formFields: unknown) => Promise<unknown>
(submitForm: ISubmitFormType) => {...}