如何使用TypeScript制作点击事件处理函数

时间:2019-02-11 06:15:22

标签: reactjs typescript

我正在尝试为点击添加事件侦听器,但这是说在EventTarget类型上不存在classList。

class UIModal extends React.Component<Props> {
    handleClick = (e: Event) => {
        if ((e.target as EventTarget).classList.contains('modal-mask')) {
            this.props.close();
        }
    }

    componentDidMount() {
        window.addEventListener('click', this.handleClick);
    }

    componentWillUnmount() {
        window.removeEventListener('click', this.handleClick);
    }

    render() {
        return (
            <div className="modal-mask">
                <div className="modal">
                    {this.props.children}
                </div>
            </div>
        );
    }
}

2 个答案:

答案 0 :(得分:2)

也许您应该尝试e.target as Element

答案 1 :(得分:0)

e.target应该是e.currentTarget

https://github.com/Microsoft/TypeScript/issues/299

对此有一些讨论