gpt4 book ai didi

react-native - Formik handleChange - 使用钩子(Hook)

转载 作者:行者123 更新时间:2023-12-02 19:28:57 24 4
gpt4 key购买 nike

在安装 Formik 之前,我的输入如下所示:

         const [search, setSearch] = useState('');
....

<View style={styles.profileEditContainer__top}>
<TextInput
style={styles.profileEditContainer__form}
autoCapitalize="none"
placeholder="Enter what you want to create.."
placeholderTextColor={Colors.formPlaceHolderDefault}
name="search"
type="search"
value={search}
onChangeText={(e) => setSearch(e)}
autoCorrect={false}
defaultValue={search}
/>
<Button
disabled={!search}
title="Create"
onPress={(e) => {
createNewCar(e);
}}
/>
</View>

onChangeText 中,我会将输入的每个字符设置为名为 search 的状态属性。我输入的每一个键都会调用一个 API 来从数据库中获取一些数据。

例如:

如果我在输入中输入 h,数据库将返回 2 辆汽车 honda, hyundai

我读到 Formik 可以简化 React 中的很多表单设置,所以我下载了它,但是,Formik 的 handleChange 属性想要跟踪 values.search

         <Formik
initialValues={{
search,
}}
onSubmit={(values) => {
console.log('values', values);
}}>
{({ handleChange, handleSubmit, values }) => (
<View style={styles.profileEditContainer__top}>
<TextInput
style={styles.profileEditContainer__form}
autoCapitalize="none"
placeholder="Enter what you want to create.."
placeholderTextColor={Colors.formPlaceHolderDefault}
autoCorrect={false}
value={values.search}
onChangeText={(e) => {
handleChange(values.search);
setSearch(e);
}}
/>
<Button
disabled={!search}
title="Create"
onPress={handleSubmit}
/>
</View>
)}
</Formik>

现在我无法在表单中输入内容,因为 value 指向 values.search 而不是像原来那样指向 search

问题

如何在 onChangeText 中触发 setSearch,同时将 search 添加到 formik values 属性中?

最佳答案

您可以使用setFieldValue('search', e.target.value)代替handleChange(),将代码更改为以下内容:

<Formik
initialValues={{
search,
}}
onSubmit={(values) => {
console.log('values', values);
}}>
{({ handleChange, handleSubmit, values, setFieldValue }) => (
<View style={styles.profileEditContainer__top}>
<TextInput
style={styles.profileEditContainer__form}
autoCapitalize="none"
placeholder="Enter what you want to create.."
placeholderTextColor={Colors.formPlaceHolderDefault}
autoCorrect={false}
value={values.search}
onChangeText={(e) => {
//handleChange(values.search);
setFieldValue('search', e.target.value)

setSearch(e);
}}
/>
<Button
disabled={!search}
title="Create"
onPress={handleSubmit}
/>
</View>
)}
</Formik>

关于react-native - Formik handleChange - 使用钩子(Hook),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62092886/

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