google-maps-react infoWindow onChange问​​题

时间:2018-12-13 16:06:31

标签: reactjs state onchange infowindow google-maps-react

How to add a button in infowindow with 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)
  }

谢谢!

1 个答案:

答案 0 :(得分: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} />;
  }
}

Demo

相关问题