我在受控组件中有一个标记列表和一个输入字段,用于在列表中搜索特定查询。然后我有一个地图组件,它是标记列表组件的同级组件。当我在输入中搜索特定文本时,标记列表会更新,但地图不会使用标记列表中的标记进行更新。
import React, { Component } from 'react'
import escapeRegExp from 'escape-string-regexp'
import sortBy from 'sort-by'
class MarkerList extends Component {
state = {
query: ''
}
//input onChange handler
updateQuery = (query) => {
this.setState({ query: query.trim() })
}
render() {
const { listIsOpen,
toggleList,
venues,
handleListItemClick,
} = this.props
let venuesHasValue = false
let markers = []
//check whether venues array is valid
if(venues !== undefined && venues.length > 0 && venues!== null) {
venuesHasValue = true
}
//if venues array is not empty then loop through and return only
//data that is needed
if (venuesHasValue) {
let marker = {}
venues.map(venue => {
marker = {
lat: venue.location.lat,
lng: venue.location.lng,
title: venue.name,
venueId: venue.id,
streetNumber: venue.location.formattedAddress[0],
postCode: venue.location.formattedAddress[3],
}
markers.push(marker)
})
}
let showingMarkers
if (this.state.query) {
const match = new RegExp(escapeRegExp(this.state.query), 'i')
showingMarkers = markers.filter((marker) => match.test(marker.title))
} else {
showingMarkers = markers
}
//sort list alphabetically
showingMarkers.sort(sortBy('title'))
return (
<div>
{listIsOpen ? (
<div className='marker-list-open'>
<label htmlFor='search'>Search</label>
<input
id='search'
type='text'
placeholder='search for burger or pizza'
aria-required='true'
className='list-filter'
value={this.state.query}
onChange={(e) => this.updateQuery(e.target.value)}
/>
<div className='marker-list-container'>
<ul className='venue-list'>
{showingMarkers.map((marker, index) => {
return (
<li
tabIndex='0'
key={index}
placeholder={'search for burger or pizza'}
onClick={() => handleListItemClick(marker.venueId, marker)}
>{marker.title}</li>
)
})}
</ul>
<div className='list-toggle-close'>
<img className='toggle-icon' src={require('../images/menu.svg')} alt='list closer' onClick={toggleList} />
</div>
</div>
</div>
) : (
<div className='marker-list-closed'>
<div className='list-toggle-open'>
<img className='toggle-icon' src={require('../images/menu.svg')} alt='list opener'
onClick={toggleList} />
</div>
</div>
)}
</div>
)
}
}
export default MarkerList
如何传递经过过滤的标记showingMarkers
来映射容器组件,以便其相应地更新?
答案 0 :(得分:0)
您应将标记保持在“地图组件”状态。然后,您可以将处理程序作为Map组件的支持传递给MarkerList。 showingMarker
更新之后,您应该setState
具有更新标记的Map组件列表如下:
<MarkerList
markersHandler={this.onMarkerUpdate}
/>
onMarkerUpdate将更新地图组件的状态:
onMarkerUpdate = (markers) => {
this.setState({
markers
});
}
在您的markerList
中,您可以在处理程序中传递更新的标记列表,这将更新您的地图组件状态:
this.props.markerHandler(showingaMarkers);
最后,您可以在地图组件中从状态渲染标记:
render(){
const { markers } = this.state;
return (
<GoogleMap
//google map props
>
markers.map((marker,i)=>{
<Marker
key={i}
// your marker props
/>
});
)
}
</GoogleMap>
PS(如果可以显示地图组件)。这将更容易为您提供帮助。您可以在codeandbox上共享。