gpt4 book ai didi

reactjs - 如何将 react native 复选框与 formik 集成

转载 作者:行者123 更新时间:2023-12-02 16:30:03 27 4
gpt4 key购买 nike

注意:我们不能使用任何其他库,例如 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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com