reactjs - google-maps-react infoWindow onChange 问题
问题描述
如何使用 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)
}
提前致谢!
解决方案
我相信在您的示例中组件状态正在正确更新,显然这种行为与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} />;
}
}
推荐阅读
- c++ - 从 C++ 中具有多重继承的类派生的类:派生类正在尝试调用根基类构造函数
- javascript - 将 DIV 包裹在使用 appendChild 创建的超链接周围
- c# - iText 7水印画布在某些特殊的3d pdf中未正确显示
- python - 在 Python 中,我试图读取 excel 文件的第 5 行并在 IF 语句中使用它
- sql-server - 使用 T-SQL 提取两个字符之间的数据
- c++ - 使用 C++ 和 g++ 从 mysql.h 获取输出时出错
- html - 安装 MongoDB 时破坏了我的终端
- javascript - eslint 解析错误:使用 firebase 设置后无法读取文件 'c:\user\repo\ts-project\tsconfig.json'
- qt - 如何在 Qt 中使用 vlc-qt libvlc 从视频中读取元数据
- angular-material - 自定义日期过滤器没有返回任何东西 Angular 8