reactjs - 如何使用 google-maps-react 在信息窗口中添加按钮?
问题描述
我想在我的信息窗口中集成一个按钮。它出现了,我可以点击它,但它不会触发 onClick。
这是帖子的详细信息,我想我不能再解释了。这是帖子的详细信息,我想我不能再解释了。这是帖子的详细信息,我想我不能再解释了。
我的代码:
export class MapPage extends Component {
state = {
activeMarker: {},
selectedPlace: {},
selectedText: {},
selectedId: {},
showingInfoWindow: false
};
send = () => {
console.log('fzf');
}
onMarkerClick = (props, marker) => {
this.setState({
activeMarker: marker,
selectedPlace: props,
selectedText: props,
selectedId: props,
showingInfoWindow: true
});
};
onInfoWindowClose = () =>
this.setState({
activeMarker: null,
showingInfoWindow: false
});
onMapClicked = () => {
if (this.state.showingInfoWindow)
this.setState({
activeMarker: null,
showingInfoWindow: false
});
};
handleClick = () => {
this.setState({ open: true });
};
handleClose = (event, reason) => {
if (reason === 'clickaway') {
return;
}
this.setState({ open: false });
};
render() {
const { classes } = this.props;
return (
<div>
<Map google={this.props.google}
onClick={this.onMapClicked}
zoom={13}
initialCenter={{
lat: 48.724865087482755,
lng: -3.4469044744779467
}}
>
<Marker>
name='Paris'
onClick={this.onMarkerClick}
position={{ lat: 48, lng: -3 }}
/>
<InfoWindow
marker={this.state.activeMarker}
onClose={this.onInfoWindowClose}
visible={this.state.showingInfoWindow}>
<div>
<h2>{this.state.selectedPlace.name}</h2>
<p>{this.state.selectedPlace.description}</p>
<button type="button" onClick={this.send}>Click Me</button>
</div>
</InfoWindow>
</Map>
</div>
);
}
}
export default GoogleApiWrapper({
apiKey: ('APIKEY')
})(MapPage)
解决方案
InfoWindow
组件在库中的实现方式google-maps-react
不支持将事件处理程序附加到信息窗口动态内容。类似的问题已在此线程中讨论过。
解决方案是将 InfoWindow 子节点渲染到 DOM 节点中,以防止丢失 React 上下文,可以为此引入以下组件:
export default class InfoWindowEx extends Component {
constructor(props) {
super(props);
this.infoWindowRef = React.createRef();
this.contentElement = document.createElement(`div`);
}
componentDidUpdate(prevProps) {
if (this.props.children !== prevProps.children) {
ReactDOM.render(
React.Children.only(this.props.children),
this.contentElement
);
this.infoWindowRef.current.infowindow.setContent(this.contentElement);
}
}
render() {
return <InfoWindow ref={this.infoWindowRef} {...this.props} />;
}
}
现在一旦InfoWindow
被InfoWindowEx
事件处理程序替换,就可以附加到组件子级:
<InfoWindowEx
marker={this.state.activeMarker}
visible={this.state.showingInfoWindow}>
<button type="button" onClick={this.showDetails}>
Show details
</button>
</InfoWindowEx>
推荐阅读
- python - int() 参数必须是字符串或数字,而不是 'NoneType'
- linux - 如何使用shell从txt中读取一些数据
- c++ - 如果 arr 是一个数组,C++ 中的 *&arr 和 *&arr[0] 有什么区别?
- r - 需要帮助修改 R 中的森林图代码
- reactjs - 从 React 向 Spring REST 发送授权请求
- debian - Debian 发行版特定控制文件
- c# - 如何在运行时读取或捕获跟踪消息并使用 C# 将它们存储在字符串中?
- javascript - 命中 API 端点的 Angular 材料数据表
- database - Haskell 持久化 - 通过外键获取价值
- python - 尝试使用 sqlite3 插入多行数据(类型错误与编程错误)