gpt4 book ai didi

reactjs - 如何在formik中设置值?

转载 作者:行者123 更新时间:2023-12-04 11:36:20 24 4
gpt4 key购买 nike

我正在使用 React Native 中的功能组件,我想将图像 URI 存储在 Formik 的初始状态中。

我在 _pickimage 函数中获取图像 URI,但我不知道如何将其传递给 Formik 的初始状态。

如何将 URI 值设置为初始状态。



是否有办法将其他自定义值从功能状态存储到 Formik 初始状态?

import React, { useState } from 'react';
import { View, TextInput, Picker, Text, Button } from 'react-native';
import { globalStyles } from '../styles/global'
import { Formik } from "formik";
import * as ImagePicker from 'expo-image-picker';
import Constants from 'expo-constants';
import * as Permissions from 'expo-permissions';

export default function form(props) {
const { register } = props
const getPermissionAsync = async () => {
if (Constants.platform.ios) {
const { status } = await Permissions.askAsync(Permissions.CAMERA_ROLL);
if (status !== 'granted') {
alert('Sorry, we need camera roll permissions to make this work!');
}
}
}
const _pickImage = async () => {
getPermissionAsync();
let result = await ImagePicker.launchImageLibraryAsync({
mediaTypes: ImagePicker.MediaTypeOptions.All,
allowsEditing: true,
aspect: [4, 3],
quality: 1
});
if (!result.cancelled) {
console.log(result.uri)
// Getting Image URI value here
}
}
return (
<View >
<Formik
initialValues={
{
image: '',
}}

onSubmit={(values, actions) => {
register(values);
console.log(values);
actions.resetForm();
}}
>
{
(formikprops) => (
<View>
<Button
title="image"
icon="add-a-photo" mode="contained"
onPress={() => { _pickImage(formikprops.handleChange('image')) }}
/>
{formikprops.values.image && formikprops.values.image.length > 0 ?
<Image source={{ uri: formikprops.values.image }} style={{ width: 200, height: 200 }} /> : null}

<Button title="submit" color="coral" onPress={formikprops.handleSubmit} />
</View>
)
}
</Formik>

</View>

)
}

最佳答案

您可以使用 setFieldValue来自 formik 的函数 like

const _pickImage = async (setFieldValue, field) => {
getPermissionAsync();
let result = await ImagePicker.launchImageLibraryAsync({
mediaTypes: ImagePicker.MediaTypeOptions.All,
allowsEditing: true,
aspect: [4, 3],
quality: 1
});
if (!result.cancelled) {
console.log(result.uri)
// Getting Image URI value here
setFieldValue(field, result.uri)
}
}

----

<Button
title="image"
icon="add-a-photo" mode="contained"
onPress={() => { _pickImage(formikprops.setFieldValue, 'image') }}
/>

关于reactjs - 如何在formik中设置值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61446346/

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