React.js中点击class为report-btn的按钮时如何实现页面重定向
解决方案
你当前的举报按钮没有绑定点击事件,且InfoWindow由谷歌地图动态渲染,直接用原生方法绑定事件容易失效,直接在React层面绑定处理逻辑即可,按你实际的跳转场景选择对应方案:
方案1:跳转到外部页面
直接在类组件中新增点击处理函数,绑定到按钮上即可,修改后的完整代码如下:
export class MapContainer extends Component { state = { showingInfoWindow: false, activeMarker: {}, selectedPlace: {}, }; onMarkerClick = (props, marker, e) => this.setState({ selectedPlace: props, activeMarker: marker, showingInfoWindow: true, }); onClose = (props) => { if (this.state.showingInfoWindow) { this.setState({ showingInfoWindow: false, activeMarker: null, }); } }; // 新增举报按钮点击处理逻辑 handleReportClick = () => { // 替换为你要跳转的目标页面地址 window.location.href = '你的目标跳转地址' // 如果需要携带当前选中地点的参数可以这么写 // window.location.href = `你的目标跳转地址?place=${encodeURIComponent(this.state.selectedPlace.name)}` } render() { return ( <Map google={this.props.google} zoom={14} style={mapStyles} initialCenter={{ lat: 40.75901, lng: -73.984474, }} > <Marker onClick={this.onMarkerClick} name={"S Train - 42 Street"} /> <InfoWindow marker={this.state.activeMarker} visible={this.state.showingInfoWindow} onClose={this.onClose} > <div> <h4>{this.state.selectedPlace.name}</h4> {/* 给按钮绑定点击事件 */} <button className="report-btn" onClick={this.handleReportClick}>Report</button> </div> </InfoWindow> </Map> ); } }
方案2:React单页应用内部路由跳转
如果是跳转到你项目内的其他路由页面,按你使用的React Router版本处理即可:
- 若使用
react-router v5,给当前组件包一层withRouter高阶组件,之后在handleReportClick里调用this.props.history.push('/你的内部路由地址')即可实现跳转 - 若使用
react-router v6,可以把类组件改写成函数组件,用useNavigate钩子实现路由跳转,也可以自定义高阶组件给类组件注入navigate方法使用。
内容的提问来源于stack exchange,提问作者mw3981
相关产品推荐
相关产品推荐

