Cha*_*Lee 1 typescript reactjs formik
将 Reactjs 与打字稿结合使用
我想将 useFormik 挂钩传递给组件道具。
这样做的原因是为了减少不必要的线路并增加重用。
我当前的代码
...
const formik = useFormik({
initialValues: { userName: ''},
validationSchema,
onSubmit: (values) => {}
})
return (
<Form>
{/* A place to make a component. */}
<Text
id="userName"
fullWidth
label="Name"
defaultValue={formik.values.userName}
onChange={formik.handleChange}
onBlur={formik.handleBlur}
error={formik.touched.userName && Boolean(formik.errors.userName)}
helperText={formik.touched.userName && formik.errors.userName}
>
{/* A place to make a component. */}
</Form>
)
Run Code Online (Sandbox Code Playgroud)
自定义组件,这是问题的要点。
interface props {
id: string;
formik : what, // How do I deliver the prop here?
}
const TextFieldCustom = ({ id, formik }: props) => {
return (
<Text
id={id}
fullWidth
label={id}
defaultValue={formik.values.userName}
onChange={formik.handleChange}
onBlur={formik.handleBlur}
error={formik.touched.userName && Boolean(formik.errors.userName)}
helperText={formik.touched.userName && formik.errors.userName}
>
);
};
Run Code Online (Sandbox Code Playgroud)
由于您的回答,我的代码完成了。
...
const formik = useFormik({
initialValues: { userName: ''},
validationSchema,
onSubmit: (values) => {}
})
return (
<Form>
{/* A place to make a component. */}
<TextFieldCustom id="username" formik={formik}/>
{/* A place to make a component. */}
</Form>
)
Run Code Online (Sandbox Code Playgroud)
我想要你好的解决方案。
小智 6
如果你想从子组件访问 formik 助手,你可以使用 useFormikContext。我认为这更容易。
从您的代码中,我还建议使用 Formik 组件作为 Form 组件的父级,因为它需要它,但这可能是另一回事。
这就是我要做的(请注意,我已经用表单 html 标签替换了 Form 组件):
父组件:
export interface IFormData {
username: string;
}
const validationSchema = Yup.object().shape({
userName: Yup.string()
.required("Username required"),
});
const ParentComponent = () => {
const formikConfig = useFormik({
initialValues: { userName: "" },
validationSchema,
onSubmit: (values) => {},
});
return (
<form onSubmit={formikConfig.handleSubmit}>
<TextCompo id="id" />
</form>
);
};
export default ParentComponent;
Run Code Online (Sandbox Code Playgroud)
儿童组件:
interface ITextCompoProps {
id: string;
}
const TextFieldCustom = (props: ITextCompoProps) => {
const { id } = props;
const context = useFormikContext<IFormData>();
return (
<Text
id={id}
fullWidth
label={id}
defaultValue={context.values.userName}
onChange={context.handleChange}
onBlur={context.handleBlur}
error={!!(context.errors.username && context.touched.username)}
helperText={context.touched.username && context.errors.username}
/>
);
};
export default TextFieldCustom;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5594 次 |
| 最近记录: |