【发布时间】:2019-12-26 13:58:12
【问题描述】:
我有一个formik 表单,如下所示。我可以在 formik 组件中提交表单。但是我怎么能在formik组件之外提交它(这个例子的页脚按钮里面)。
Formik 网址:Click here
特别是,我如何在Formik 组件之外访问此值handleChange, values, handleSubmit, errors,isValid,touched, handleBlur, isSubmitting,。
我在 react-native 中做这件事,但我想 react 的概念会有所帮助,特别是在使用 useRef 等的情况下。在网上找到了几个使用 ref 的示例,但没有一个有效。
<View>
<Formik
onSubmit={async values => {
this.handleSubmit(values);
await new Promise(resolve => setTimeout(resolve, 1000));
console.warn(values);
}}
validationSchema={validationSchema}>
{({
handleChange,
values,
handleSubmit,
errors,
isValid,
touched,
handleBlur,
isSubmitting,
}) => (
<View>
<Form>
<Text>First Name</Text>
<TextInput
name="first_name"
value={values.first_name}
onChangeText={handleChange('first_name')}
/>
{errors.first_name ? (
<Text>{errors.first_name}</Text>/>
) : (
<></>
)}
<Button onPress={handleSubmit}>
<Text>Submit</Text>
</Button>
</Form>
</View>
)}
</Formik>
<Footer>
<Button>Submit</Button>
</Footer>
</View>
【问题讨论】:
-
为什么不在
<Formik />中包含<Footer />? -
@Rawrplus 那是因为页脚组件应该位于表单的底部并保持在绝对位置。而表单部分是可滚动的(表单实际上有 10+ 输入字段)。因此,将页脚放在表单中是没有意义的。这只是一种情况的示例。表单提交按钮可以位于页眉/页脚或任何地方。其核心是在 formik 组件之外进行表单提交。希望这对你有意义。
标签: reactjs react-native