在一个控制器上形成多个控件的反作用钩子



我有一个文本输入组件,它使用来自react原生纸的文本输入,我想通过调用google place autocomplete API 来实现一个地方自动完成

现在我可以显示建议,但我不能用已单击的建议的值更改文本输入值组件的屏幕截图

由于我使用了react hook表单中的Controller,我想我可以使用useForm中的setValue来更改值,但当我试图调用setValue将textInput值更改为建议值时,它什么也没做

import React from "react";
import { FlatList, StyleSheet, TouchableOpacity, View } from "react-native";
import { Text, TextInput, Colors } from "react-native-paper";
import { Controller, useForm } from "react-hook-form";
import axiosInstance from "services/axiosInstance";
export default React.forwardRef(
(
{
name,
label,
placeholder,
control,
style: addOnStyle,
...props
},
ref
) => {
const { setValue } = useForm();
const [addressList, setAddressList] = React.useState([])
const getAddressList = async (input) => {
if (input == null || input.match(/^ *$/) !== null) {
setAddressList([])
} else {
const response = await axiosInstance.get(
`https://maps.googleapis.com/maps/api/place/autocomplete/json?input=${input}&components=country:us&language=en&key=API_KEY`
)
setAddressList([])
if (response?.data?.status === "OK") {
response?.data?.predictions?.map((item) => setAddressList(addressList => [...addressList, item.description]))
} else {
setAddressList(["Address not found."])
}
}
}
return (
<View style={{ ...styles.viewInput, ...addOnStyle }}>
<Controller
control={control}
name={name}
defaultValue=""
render={({
field: { onChange, onBlur, value, name },
fieldState: { error },
}) => {
return (
<>
<TextInput
label={label}
name={name}
placeholder={placeholder}
onBlur={onBlur}
onChangeText={(val) => onChange(val, getAddressList(val))}
error={!!error?.message}
value={value}
ref={ref}
{...props}
/>
{error?.message ? (
<Text style={styles.textError}>{error?.message}</Text>
) : null}
{addressList.length > 0 ?
<View style={styles.addressListContainer}>
<FlatList
keyExtractor={(_, i) => String(i)}
data={addressList}
renderItem={({ item, index }) => {
return (
<TouchableOpacity 
activeOpacity={1} 
style={[styles.addressListItem, index==0 ? {borderTopWidth: 0} : {borderTopWidth: 1}]}
onPress={() => {setAddressList([]), setValue(name, item)}}
>
<Text numberOfLines={1}>{item}</Text>
</TouchableOpacity>
)
}}
/>
</View>
: null}
</>
);
}}
/>
</View>
);
}
);

更新更改标题以匹配当前问题

我认为目前我的问题是,由于控件是从组件外部设置的,因此无法使用组件内部的setValue进行更改,现在我想知道我们是否可以在一个控制器上使用多个控件?

我通过将onPress上的setValue(name,item(更改为onChange(item(来解决它,它不需要另一个控制

最新更新