我无法在此代码中设置状态。我理解它是因为我没有绑定功能getvalue。否则,我无法调用this.radius。我这段代码this.radius是5000。如果我将其更改为
getvalues = (e)=> { console.log(e)}
返回未定义。
那我该怎么办
class Mapspage extends React.Component {
constructor(props) {
super(props);
this.state = {
location: { lat: 52.2387683, lng: 5.8322737 },
position: [],
radius: 5000,
};
}
getvalues(e) {
this.setState({'radius': this.radius});
}
render() {
const MapWithAMarker = withGoogleMap(props => (
<GoogleMap
defaultZoom={11}
defaultCenter={this.state.location}
>
<Circle
radius={this.state.radius}
editable={true}
onRadiusChanged={this.getvalues}
onDragEnd={this.getvalues}
draggable={true}
visible={true}
center={this.state.location}
/>
</GoogleMap>
));
return (
<div className="box box-default">
<MapWithAMarker
containerElement={<div style={{ height: `400px` }} />}
mapElement={<div style={{ height: `100%` }} />}
/>
</div>
);
}
}
答案 0 :(得分:1)
我找到了答案。您需要引用圆组件,然后可以调用getValues函数。另外,您还需要返回false false shouldComponentUpdate
这是代码
class Mapspage extends React.Component {
constructor(props) {
super(props);
this.state = {
location: { lat: 52.2387683, lng: 5.8322737 },
position: [],
radius: 5000
};
}
mapMounted = ref => {
this.map = ref;
};
shouldComponentUpdate(nextProps, nextState) {
return false;
}
getvalues = e => {
const radius = this.map.getRadius();
const center = this.map.getCenter();
this.setState({ radius: radius });
this.setState({
"location.lat": center.lat(),
"location.lng": center.lng()
});
};
render() {
const MapWithAMarker = withGoogleMap(props => (
<GoogleMap defaultZoom={11} defaultCenter={this.state.location}>
<Circle
ref={this.mapMounted.bind(this)}
radius={this.state.radius}
editable={true}
onRadiusChanged={props.getval}
onDragEnd={props.getval}
draggable={true}
visible={true}
center={this.state.location}
/>
</GoogleMap>
));
return (
<div className="box box-default">
<MapWithAMarker
getval={this.getvalues.bind(this)}
containerElement={<div style={{ height: `400px` }} />}
mapElement={<div style={{ height: `100%` }} />}
/>
</div>
);
}
}
答案 1 :(得分:-1)
请尝试此操作,问题似乎出在绑定方面。
class Mapspage extends React.Component {
constructor(props) {
super(props);
this.state = {
location: { lat: 52.2387683, lng: 5.8322737 },
position: [],
radius: 5000,
};
}
getvalues = (e) => {
this.setState({radius: this.radius});
}
render() {
const MapWithAMarker = withGoogleMap(props => (
<GoogleMap
defaultZoom={11}
defaultCenter={this.state.location}
>
<Circle
radius={this.state.radius}
editable={true}
onRadiusChanged={this.getvalues}
onDragEnd={this.getvalues}
draggable={true}
visible={true}
center={this.state.location}
/>
</GoogleMap>
));
return (
<div className="box box-default">
<MapWithAMarker
containerElement={<div style={{ height: `400px` }} />}
mapElement={<div style={{ height: `100%` }} />}
/>
</div>
);
}
}