问题描述
注意:我们不能仅使用“ react-native”和“ formik”之类的其他库,例如react-native-element。
我无法将react-native复选框与formik集成在一起。需要设置formik表格的值。
如果我将InputFields与formic一起使用,则它正在使用相同的代码。
CheckBox.js
import React from 'react';
import { CheckBox,Text,StyleSheet,View } from 'react-native';
const CheckBox = ({ children,value,handleChange }) => {
return (
<View>
<View>
<CheckBox
type={'checkBox'}
value={value}
onValueChange={handleChange}
checked={value}
/>
<Text>{children}</Text>
</View>
</View>
);
};
export default CheckBox;
Main.js
<Formik
initialValues={{
financiallyResponsible: true,}}
onSubmit={(values,{ resetForm }) => {
console.log(values);
}}
>
{({
handleChange,handleSubmit,values,}) => (
<View>
<CheckBox
value={values?.financiallyResponsible}
handleChange={handleChange('financiallyResponsible')}
>
Financially Responsible
</CheckBox>
<Button onPress={handleSubmit} title="Submit"></Button>
</View>
)}
</Formik>
);
}
解决方法
您可以像doc这样使用setFieldValue(fieldName,nextValue)
:
...而不是直接将回调分配给道具,因为我们 必须从某个地方获取fieldName,并使用React Native 不能像在网络中那样自动获取(使用输入名称属性)。 您还可以使用setFieldValue(fieldName,value)和 setFieldTouched(fieldName,bool)作为替代。
Checkbox.js
import React from 'react';
import { CheckBox,Text,StyleSheet,View } from 'react-native';
const Checkbox = ({ children,...props }) => {
return (
<View>
<View>
<CheckBox
type={'checkbox'}
{...props}
/>
<Text>{children}</Text>
</View>
</View>
);
};
export default Checkbox;
Main.js
<Formik
initialValues={{
financiallyResponsible: true,}}
onSubmit={(values,{ resetForm }) => {
console.log(values);
}}
>
{({
handleChange,handleSubmit,values,setFieldValue
}) => (
<View>
<Checkbox
value={values?.financiallyResponsible}
onValueChange={nextValue => setFieldValue('financiallyResponsible',nextValue)}
>
Financially Responsible
</Checkbox>
<Button onPress={handleSubmit} title="Submit"></Button>
</View>
)}
</Formik>
);
}
,
这有助于使其正常工作,但谢谢@Bruno,您的建议对我有所帮助。
checkbox.js
<View>
<View>
<CheckBox
type={'checkbox'}
value={value}
onValueChange={handleChange}
// checked={value}
{...props}
/>
<Text>{children}</Text>
</View>
</View>
Main.js
<Formik
initialValues={{
financiallyResponsible: true,setFieldValue
}) => (
<View>
<Checkbox
value={values?.financiallyResponsible}
handleChange={nextValue => setFieldValue('financiallyResponsible',nextValue)}
>
Financially Responsible
</Checkbox>
<Button onPress={handleSubmit} title="Submit"></Button>
</View>
)}
</Formik>
);
}