html - 模拟点击 React 元素

标签 html reactjs events mouseevent

我将 React 与 Leaflet 一起使用,并希望在组件安装后立即启动绘图菜单,而无需让用户单击任何按钮。 React Leaflet Draw API 在这方面有点不透明,我想做的就是以编程方式触发对适当按钮的点击,而无需用户这样做。然后我会隐藏按钮。

问题是我在使用 .click() 或 MouseEvent('click') API 时运气不好。这是我对后者的尝试:

import React, { Component } from 'react';
import { connect } from 'react-redux';
import * as actions from '../../../actions';
import { Polygon, FeatureGroup } from 'react-leaflet';
import { EditControl } from 'react-leaflet-draw';

export class DrawNewPlot extends Component {
    componentDidMount() {
        let simulateClick = elem => {
            let evt = new MouseEvent('click', {
                bubbles: true,
                view: window
            });
        };
        let drawControl = document.getElementsByClassName('leaflet-draw-toolbar');
        simulateClick(drawControl);
    }
    render() {
        return (
            <FeatureGroup>
                <EditControl
                    position="bottomright"
                    onEdited={e => {
                        e.layers.eachLayer(a => {
                            this.props.setNewPlotGeojson(a.toGeoJSON());
                        });
                    }}
                    onCreated={e => {
                        this.props.setNewPlotGeojson(e.layer.toGeoJSON());
                    }}
                    draw={{
                        marker: false,
                        circle: false,
                        rectangle: false,
                        polygon: true,
                        polyline: false,
                        circlemarker: false,
                        edit: false
                    }}
                    edit={{ edit: false }}
                />
            </FeatureGroup>
        );
    }
}

function mapStateToProps(state) {
    return {
        addingNewPlotDetails: state.plots.addingNewPlotDetails
    };
}

export default connect(mapStateToProps, actions)(DrawNewPlot);

关于我做错了什么有什么想法吗?

最佳答案

您的 simulateClick 方法创建事件,但从不调度它。尝试添加 elem.dispatchEvent(evt);

虽然我必须补充一点,以这种方式模拟鼠标点击只是为了触发一些初始的副作用感觉不对。我不熟悉 Leaflet,但值得检查一下他们是否有一些 API 来设置初始状态

关于html - 模拟点击 React 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48042613/

相关文章:

reactjs - react native 0.31 : Could not get BatchedBridge Error

javascript - jQuery ul 事件目标 - 我可以找到实际上是事件目标的 li 吗?

javascript - 添加同类事件是否会追加或覆盖之前添加的同名事件?

c# - 哪个事件捕获对 RichTextBox 的每次编辑?

javascript - 如何使用 SwiftSoup 抓取重定向的特定网站?

javascript - 在不重新加载整个页面的情况下重新加载 DIV

html - 对齐和图像文本 -- HTML div

android - 错误 : Unable to resolve dependency for ':react-native-maps@debug/compileClasspath' : Could not resolve androidx. appcompat :appcompat:1. 0.0

css - li 元素内的 div 显示 block 使其有空白空间

css - 将空间分成3个平行 block