我在React native中有一个Formik表单,其中我有一个包含一系列问题的字段数组。问题中的一个具有用户可以从中选择的自定义组件,如果他们选择“更改任何轮胎”,则会出现另一个组件。这很好用,但我似乎无法弄清楚如何仅针对它们所在的数组项。它出现在所有数组项中。
任何帮助将不胜感激。
<Formik
enableReinitialize={true}
initialValues={initialState}
validationSchema={validationSchema}
onSubmit={(values, actions) => {
console.log(values);
}}
>
{props => (
<Form>
<View>
<MyDatePicker
label="Date"
name="tsDate"
/>
<FieldArray
name="timesheets"
render={arrayHelpers => (
<>
{props.values.timesheets &&
(
props.values.timesheets.map((timesheet, index) => (
<View>
<Select
label="Have you..."
name={`timesheets.[${index}].accessory`}
items={[
{ label: 'N/A', value: 'N/A', key: 1 },
{ label: 'useed a Light Vehicle', value: 'useed a Light Vehicle', key: 2 },
{ label: 'changed any GET', value: 'changed any GET', key: 3 },
{ label: 'changed any Tyres', value: 'changed any Tyres', key: 4 },
{ label: 'used a Rock Breaker', value: 'used a Rock Breaker', key: 5 },
{ label: 'used a Trailer', value: 'used a Trailer', key: 6 },
{ label: 'used a GPS', value: 'used a GPS', key: 7 },
]}
/>
{(props.values.timesheets.some((timesheet) => (timesheet.accessory === ('changed any Tyres') )) )
?
<View>
<Select
label="What type of Tyres"
name={`timesheets.[${index}].tyresType`}
items={[
{ label: 'Front RH, LH', value: 'Front RH, LH', key: 1 },
{ label: 'Rear RH, LH', value: 'Rear RH, LH', key: 2 },
{ label: 'Spare', value: 'Spare', key: 3 },
]}
/>
</View>
:
<View>
{console.log('Hide Rock Breaker!')}
</View>
}
{props.values.timesheets.length === 1 ? (
<View style={{ flexDirection: 'row', justifyContent: 'center', paddingTop: 20, paddingBottom: 0 }}>
<TouchableOpacity style={cvstyles.arrayButtons} onPress={() => arrayHelpers.push(index, '')}>
<Text style={{ color: '#fff' }} >Add Entry</Text>
</TouchableOpacity>
</View>
) : (
<View style={{ flexDirection: 'row', justifyContent: 'space-between', paddingTop: 20, paddingBottom: 0 }}>
<TouchableOpacity style={cvstyles.arrayButtons} onPress={() => arrayHelpers.push(index, '')}>
<Text style={{ color: '#fff' }} >Add Entry</Text>
</TouchableOpacity>
<TouchableOpacity style={[cvstyles.arrayButtons, { marginRight: '2%' }]} onPress={() => arrayHelpers.remove(index)}>
<Text style={{ color: '#fff' }} >Remove Entry</Text>
</TouchableOpacity>
</View>
)}
</View>
</>
)}
/>
</Form>
)}
</Formik>
答案 0 :(得分:0)
只需保持changeTyreSelectedOption = []
的一个数组处于状态,如果用户选择更改任何轮胎选项,则将该索引推入changeTyreSelectedOption
这样的changeTyreSelectedOption.push(index)
数组。现在显示额外组件的条件将是
{changeTyreSelectedOption.includes(index)
?
<View>
<Select
label="What type of Tyres"
name={`timesheets.[${index}].tyresType`}
items={[
{ label: 'Front RH, LH', value: 'Front RH, LH', key: 1 },
{ label: 'Rear RH, LH', value: 'Rear RH, LH', key: 2 },
{ label: 'Spare', value: 'Spare', key: 3 },
]}
/>
</View>
:
<View>
{console.log('Hide Rock Breaker!')}
</View>
}
以显示所需的组件。
注意:您还需要从index
中删除changeTyreSelectedOption
,如果用户更改选项