作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
注意:我们不能使用任何其他库,例如 react-native-element,只能使用“react-native”和“formik”。
我无法将 react-native 复选框与 formik 集成。需要设置formik表单的值。
如果我将 InputFields 与蚁酸一起使用,它会使用相同的代码。
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)
说:
... instead of directly assigning the callbacks to props, because wehave to get the fieldName from somewhere and with React Native wecan't get it automatically like in web (using input name attribute).You can also use setFieldValue(fieldName, value) andsetFieldTouched(fieldName, bool) as an alternative.
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>
);
}
关于reactjs - 如何将 react native 复选框与 formik 集成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63676803/
我是一名优秀的程序员,十分优秀!