首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >react-google-maps StandaloneSearchBox卸载

react-google-maps StandaloneSearchBox卸载
EN

Stack Overflow用户
提问于 2018-04-25 01:14:39
回答 1查看 434关注 0票数 0

我正在尝试使用https://www.npmjs.com/package/react-google-maps中的StandaloneSearchBox组件

在查看了docs和其他一些答案之后,我实现了如下组件:

代码语言:javascript
运行
复制
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组件会被卸载

EN

回答 1

Stack Overflow用户

发布于 2018-09-21 04:20:21

我不确定它是否仍然是实际的,但是要解决这个问题,你需要在你的类定义之前从render函数中提取这一部分:

代码语言:javascript
运行
复制
const Searchbox = withScriptjs(props => (....))

所以它看起来像这样:

代码语言:javascript
运行
复制
imports ...

const Searchbox = withScriptjs(props => (....))

class AddressSearchbox extends Component {
  ...
  render() {
    return (
      <Searchbox .../>
    );
  }
}

在实践中,大多数React应用程序只调用ReactDOM.render()一次。

来源:https://reactjs.org/docs/rendering-elements.html

之所以看到这种闪烁,是因为每次状态改变时,ReactJS都会运行render()函数。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50007450

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档