0

如何使用 google-maps-react 在信息窗口中添加按钮?

您好,我正在编写一个 React 应用程序,我在从 google-maps-react 更改 InfoWindow 内的状态时遇到问题,上面的解决方案帮助我克服了这个障碍。

但是,现在,我想编辑 InfoWindowEx 组件中的内容时遇到了问题。使用上面的方法,我可以更改 InfoWindowEx 中文本框的状态,但是,当我单击文本框并键入时,它会让我键入 1 个字母,然后我将不得不再次单击文本框,如果我想输入下一个字母等。我认为这个问题与状态有关。

我不知道是否有解决方案,我一直在尝试很多不同的事情,但希望有人可以帮助我知道发生了什么。

这是我的 InfoWindowEx 组件:

<InfoWindowEx
      key={currentInfoWindow.id}
      id={currentInfoWindow.id}
      marker={this.state.activeMarker}
      visible={this.state.showingInfoWindow}
      selectedPlace={this.state.selectedPlace}
      onInfoWindowClose={this.onInfoWindowClose}
    >

      <div >
        {infoWindowEditBoxes}
        {infoWindowContent}

      </div>
    </InfoWindowEx>

编辑框在条件语句中呈现,它们是:

if (this.state.editButton) {
      infoWindowEditBoxes = (

        <div>
          <input key={this.props.marker}  id="editedName" type="text" placeholder="New Bathroom Name"  onChange={this.handleTextBoxState}></input>
          <input key={this.props.marker}  id="editedLocationName" type="text" placeholder="New Bathroom Location" onChange={this.handleTextBoxState}></input>
          <button onClick={() => this.handleSubmitChangesButtonState()}>Submit Changes</button>
        </div>
      );
    }
    else {
      infoWindowEditBoxes = null
    }

这是我的状态更改功能:

 handleTextBoxState = (evt) => {
    const stateToChange = {}
    stateToChange[evt.target.id] = evt.target.value
    this.setState(stateToChange)
    console.log(stateToChange)
  }

提前致谢!

4

1 回答 1

0

我相信在您的示例中组件状态正在正确更新,显然这种行为与InfoWindowEx组件本身有关。它的实现方式setState()会导致重新渲染 InfoWindow组件,从而导致失去输入焦点。

您可以考虑以下组件的更新版本,如果它已经打开,它会阻止重新呈现信息窗口:

export default class InfoWindowEx extends Component {
  constructor(props) {
    super(props);
    this.state = {
      isOpen: false
    };
    this.infoWindowRef = React.createRef();
    this.containerElement = document.createElement(`div`);
  }

  componentDidUpdate(prevProps) {
    if (this.props.children !== prevProps.children) {
      ReactDOM.render(
        React.Children.only(this.props.children),
        this.containerElement
      );
      this.infoWindowRef.current.infowindow.setContent(this.containerElement);
      this.setState({
        isOpen: true
      });
    }
  }

  shouldComponentUpdate(nextProps, nextState) {
    if (this.state.isOpen) {
      return this.props.marker.position.toString() !== nextProps.marker.position.toString();
    }
    return true;
  }

  infoWindowClose(){
    this.setState({
      isOpen: false
    });
  }


  render() {
    return <InfoWindow onClose={this.infoWindowClose.bind(this)} ref={this.infoWindowRef} {...this.props} />;
  }
}

演示

于 2018-12-14T16:52:30.450 回答