我已决定显示/隐藏地图取决于按钮。这是我的代码:
let showingMap = true;
const toggleMapVisibility = () => {
showingMap = !showingMap;
console.log(showingMap);
};
const DetailModal = (props) => (
<Button onClick={toggleMapVisibility}>Hide/Show</Button>
{
showingMap ?
<Segment>
<MapObject
isMarkerShown
lat={props.order.user.userAddressPoint.lat}
lng={props.order.user.userAddressPoint.lng}
googleMapURL="https://maps.googleapis.com/maps/api/js?v=3.exp&libraries=geometry,drawing,places"
loadingElement={<div style={{ height: `100%` }} />}
containerElement={<div style={{ height: `400px` }} />}
mapElement={<div style={{ height: `100%` }} />}
/>
</Segment> :
null
}
}
好吧,地图正确显示了初始状态。但是,当我单击Button时,它使showingMap
变量为false,但无法隐藏地图。我没有任何错误。
有什么建议吗?
答案 0 :(得分:1)
将showingMap置于状态和toggleMapVisibility调用中
this.setState({ showingMap: !this.state.showingMap)};
答案 1 :(得分:1)
您需要更改状态或道具以重新渲染反应组件。
在这里您可以在DetailModal组件中添加本地状态。
class DetailModal extends React.Component {
state = {
showingMap: true,
}
toggleMapVisibility = () => {
this.setState((prevState) => (
{
showingMap: !prevState.showingMap
}
))
};
render() {
const { showingMap } = this.state;
const { order } = this.props;
return (
<React.Fragment>
<Button onClick={this.toggleMapVisibility}>Hide/Show</Button>
{
showingMap ?
<Segment>
<MapObject
isMarkerShown
lat={order.user.userAddressPoint.lat}
lng={order.user.userAddressPoint.lng}
googleMapURL="https://maps.googleapis.com/maps/api/js?v=3.exp&libraries=geometry,drawing,places"
loadingElement={<div style={{ height: `100%` }} />}
containerElement={<div style={{ height: `400px` }} />}
mapElement={<div style={{ height: `100%` }} />}
/>
</Segment> :
null
}
</React.Fragment>
)
}
}