【发布时间】:2020-05-20 23:14:54
【问题描述】:
步骤:用户在表单的第一个问题中做出选择。得到的答案将用于构建一系列复选框,作为表单的第二个问题。
我能够使代码达到正确呈现复选框的程度。
但我不知道在那之后该怎么办。一旦复选框被渲染,我需要复选框的值来初始化一个对象(这将是状态的一部分),它是{checkboxName1:false, checkboxName2:false} 的键值对。然后随着复选框被选中,对象将被更新。所以如果checkboxName1被用户选中,那么对象将被更新为:{checkboxName1:true, checkboxName2:false}
然后我需要使用表单的提交按钮保存整个表单(Q1 和 Q2)中的数据。第二个问题的数据将用于驱动另一个屏幕上的输出。
这个问题似乎与我正在寻找的最接近:How to set input value of one field based on another field in formik? 但他们只使用来自 Q1 的输入来驱动 Q2 的输出(而不是进一步的输入)。
这是我的基本代码:
const initialValues = {
selectedCategory: "",
};
function handleSubmit() {
console.log("Handle submit");
}
function buildIngredientsChoice(groceryCategory) {
console.log(groceryCategory);
const ingredientsInChosenCategory = indgredientCategories.filter(
(each) => each.category === groceryCategory
);
//Middle ground:
const justArrayOfIngredients =
ingredientsInChosenCategory[0]["ingredients"];
// Build obj of ingredients:
const objOfIngredientsCheckboxes = ingredientsInChosenCategory[0][
"ingredients"
].reduce((o, key) => ({ ...o, [key]: false }), {});
console.log(justArrayOfIngredients);
return justArrayOfIngredients.map((each, index) => (
<CommonCheckbox key={index} title={each}></CommonCheckbox>
));}
<Formik initialValues={initialValues} onSubmit={handleSubmit}>
{(formik) => (
<>
<View>
<Picker
// passing value directly from formik
selectedValue={formik.values.selectedCategory}
// changing value in formik
onValueChange={(itemValue) =>
formik.setFieldValue("selectedCategory", itemValue)
}
>
<Picker.Item
label="Select your category"
value={initialValues.selectedCategory}
key={0}
/>
<Picker.Item label="Produce" value="produce" key={1} />
//A bunch of items in Picker.
</View>
//This renders the checkboxes correctly but that's where U get stuck:
{formik.values.selectedCategory
? buildIngredientsChoice(formik.values.selectedCategory)
: null}
{/* submitting formik instead of calling this.handleSubmit directly */}
<Button title="Submit" onPress={formik.handleSubmit} />
</>
)}
</Formik>
如果您在 Android 手机上下载了 Expo 应用程序,您可以在此处查看该应用程序:https://expo.io/@sabbygirl99/recipe-project-mobile
【问题讨论】:
标签: javascript react-native expo formik