我正在尝试使用https://www.npmjs.com/package/react-google-maps中的StandaloneSearchBox组件
在查看了docs和其他一些答案之后,我实现了如下组件:
import React, { Component } from "react";
import PropTypes from "prop-types";
import { withScriptjs } from "react-google-maps";
import StandaloneSearchBox from "react-google-maps/lib/components/places/StandaloneSearchBox";
import { Input } from "semantic-ui-react";
import API_KEY from "../config/googleAPIkey";
class AddressSearchbox extends Component {
constructor(props) {
super(props);
this.searchboxRef = null;
}
onSearchBoxMounted = ref => {
this.searchboxRef = ref;
};
onPlacesChanged = () => {
const places = this.searchboxRef.getPlaces();
this.props.onPlaceSelect(places[0]);
};
render() {
const Searchbox = withScriptjs(props => (
<StandaloneSearchBox
ref={props.onSearchBoxMounted}
onPlacesChanged={props.onPlacesChanged}
>
<Input
type="text"
placeholder="Type address or google place name"
icon="search"
/>
</StandaloneSearchBox>
));
return (
<Searchbox
googleMapURL={`https://maps.googleapis.com/maps/api/js?key=${API_KEY}&v=3.exp&libraries=geometry,drawing,places`}
loadingElement={<div style={{ height: `100%` }} />}
onPlacesChanged={this.onPlacesChanged}
onSearchBoxMounted={this.onSearchBoxMounted}
/>
);
}
}
AddressSearchbox.propTypes = {
onPlaceSelect: PropTypes.func.isRequired
};
export default AddressSearchbox;我在一个注册表单中使用了该组件,其中所有其他输入字段都会在输入更改时更新状态,从而导致重新呈现整个表单。当AddressSearchbox组件被重新渲染时,它似乎被卸载,然后重新挂载,导致闪烁。组件本身运行良好。
编辑:在记录传递到onSearchBoxMounted()中的ref参数时,它会在每次重新呈现后打印null,然后打印SearchBox对象,因此根据this,SearchBox组件会被卸载
发布于 2018-09-21 04:20:21
我不确定它是否仍然是实际的,但是要解决这个问题,你需要在你的类定义之前从render函数中提取这一部分:
const Searchbox = withScriptjs(props => (....))所以它看起来像这样:
imports ...
const Searchbox = withScriptjs(props => (....))
class AddressSearchbox extends Component {
...
render() {
return (
<Searchbox .../>
);
}
}在实践中,大多数React应用程序只调用ReactDOM.render()一次。
来源:https://reactjs.org/docs/rendering-elements.html
之所以看到这种闪烁,是因为每次状态改变时,ReactJS都会运行render()函数。
https://stackoverflow.com/questions/50007450
复制相似问题