模拟在React元素上点击

4
我正在使用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);

有没有想法,我做错了什么?
1个回答

3
您的simulateClick方法创建了事件,但从未触发它。尝试添加elem.dispatchEvent(evt); 虽然我必须补充说,通过这种方式模拟鼠标点击只是为了触发一些初始副作用感觉不太对。我不熟悉Leaflet,但值得检查一下它们是否有一些API来设置初始状态。

我在你上面的代码中注意到另一个问题,getElementsByClassName返回的是一个数组,而不是单个元素。尝试记录并查看该类名是否与仅有1个元素匹配,如果是,则还应在末尾添加[0],即document.getElementsByClassName('leaflet-draw-toolbar')[0]; - luanped

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接