我正在使用打字稿并使用react-final-form形式进行React应用程序,我在使用一些React库来集成google place和geocoder API:“ react-places-autocomplete”:“ ^ 7.2.1 “和” react-final-form“:” ^ 6.3.0“
我遇到的问题是在用户在onSelect上选择自动完成组件提供的建议之一后,更新了react-final-form字段中的值:下面是一些代码摘录:
onSelect函数:
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
。 That's only for checkboxes and radio buttons。