模拟React元素上的单击

时间:2017-12-31 12:53:02

标签: html reactjs events mouseevent

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

麻烦的是,我没有运气使用.click()或MouseEvent('点击&#;;)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);

关于我做错了什么的想法?

1 个答案:

答案 0 :(得分:2)

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

虽然我必须添加模拟鼠标点击这种方式只是为了触发一些初始的副作用感觉不对。我不熟悉Leaflet,但是如果他们有一些API来设置初始状态

,则值得检查