我有一个formik形式,根据数组的长度将aView
与两个映射。x的长度将视情况而定。inputs
x
这是代码。
import React, { Component, Fragment } from "react";
import { Button, TextInput, View, StyleSheet } from "react-native";
import { Formik } from "formik";
class App extends Component {
render() {
const x = [1,2];
return (
<View>
<Formik
initialValues={{ name: "", description: "" }}
onSubmit={values => alert(JSON.stringify(values))}
>
{({ values, errors, handleBlur, handleChange, handleSubmit }) => (
<Fragment>
<TextInput
placeholder="name"
value={values.name}
handleBlur={() => handleBlur("name")}
onChangeText={handleChange("name")}
style={styles.input}
/>
<TextInput
placeholder="description"
value={values.description}
handleBlur={() => handleBlur("description")}
onChangeText={handleChange("description")}
style={styles.input}
/>
{x.map(x => {
return (
<View>
<TextInput key={x}
placeholder={`name`}
value={values.name}
handleBlur={() => handleBlur}
onChangeText={handleChange}
style={styles.input}
/>
<TextInput
placeholder={`description`}
value={values.description}
handleBlur={() => handleBlur(x.toString())}
onChangeText={handleChange}
style={styles.input}
/>
</View>
);
})}
<Button title="submit" onPress={handleSubmit} />
</Fragment>
)}
</Formik>
</View>
);
}
}
提交时,我无法使其正常工作。当我键入内容时,该文本还会填充该名称的所有其他输入,例如,如果我键入一个description
输入,则该文本会填充的其他所有迭代description
,我该如何进行这项工作?
看一下小吃
您需要动态创建初始值对象,以使提交正常工作,例如:
const x = [1, 2];
const initialFields = { name: "", description: "" };
const extraFields = x.map(num => ({
[`name${num}`]: "",
[`description${num}`]: ""
}));
可以将其传递给您的Formik表单,如下所示:
<Formik
initialValues={Object.assign(initialFields, ...extraFields)}
onSubmit={values => alert(JSON.stringify(values))}
>
然后将动态添加的TextInputs更改为使用这些值,如下所示:
{x.map(x => {
return (
<View>
<TextInput
placeholder={`name${x}`}
value={values[`name${x}`]}
handleBlur={() => handleBlur(`name${x}`)}
onChangeText={handleChange(`name${x}`)}
style={styles.input}
/>
<TextInput
placeholder={`description${x}`}
value={values[`description${x}`]}
handleBlur={() => handleBlur(`description${x}`)}
onChangeText={handleChange(`description${x}`)}
style={styles.input}
/>
</View>
);
})}
查看我的CodeSandbox分支以获取有效的演示。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句