是否使用onSelect函数调用更新react最终表单字段组件的值



我正在用typescript和react final表单做一个react应用程序,我正在使用一些react库来集成谷歌位置和地理编码API:"react places autocomplete":"^7.2.1">《react final-form》:"^6.3.0">

我遇到的问题是,在用户选择onSelect上的自动完成组件提供的建议之一后,更新react final表单字段中的值:以下是代码的一些摘录:

on选择功能:

const handleCitySelect = (selectedCity: string) => {
geocodeByAddress(selectedCity)
.then(results => getLatLng(results[0]))
.then(latlng => {
setCityLatLng(latlng);
}); <-- Here I need to update the field with selectedCity
};
const handleVenueSelect = (selectedVenue: string) => {
geocodeByAddress(selectedVenue)
.then(results => getLatLng(results[0]))
.then(latlng => {
setVenueLatLng(latlng);
}); <-- Here I need to update the field with selectedVenue
};

反应最终形式:

<FinalForm <-- react-final-form component
validate={validate}
initialValues={activity}
onSubmit={handleFinalFormSubmit}
render={({ handleSubmit, invalid, pristine }) => (
<Form onSubmit={handleSubmit} loading={loading}> <-- semantic-ui-react component
<Field
name="title"
placeholder="Title"
value={activity.title}
component={TextInput}
/>
<Field
name="description"
placeholder="Description"
rows={3}
value={activity.description}
component={TextAreaInput}
/>
<Field
component={SelectInput}
options={category}
name="category"
placeholder="Category"
value={activity.category}
/>
<Form.Group widths="equal">
<Field
component={DateInput}
name="date"
date={true}
placeholder="Date"
value={activity.date}
/>
<Field
component={DateInput}
name="time"
time={true}
placeholder="Time"
value={activity.time}
/>
</Form.Group>
<Field <-- field I need to update after the onSelect callback
component={PlaceInput}
name="city"
placeholder="City"
options={{ types: ["(cities)"] }}
value={activity.city}
onSelect={handleCitySelect}
/>
<Field <-- field I need to update after the onSelect callback
component={PlaceInput}
name="venue"
placeholder="Venue"
options={{
location: new google.maps.LatLng(cityLatLng),
radius: 1000,
types: ["establishment"]
}}
value={activity.venue}
onSelect={handleVenueSelect}
/>
<...>

PlaceInput是一个自定义组件,充当PlacesAutocomplete组件的包装器,该组件根据用户键入的内容执行建议。

感谢任何能提出解决方案的人。我搜索了一下互联网,找不到一个快速的解决方案,我觉得这应该是一个很容易的问题。如果需要更多的解释,请让我知道或更多的代码摘录。

干杯,

要设置字段值,PlaceInput需要调用input.onChange(newValue)

此外,您不应该将value道具传递给Field。这只适用于复选框和单选按钮。

最新更新