React组件中的嵌套addEventlistener不监听事件

时间:2019-02-22 12:06:08

标签: javascript reactjs addeventlistener

我正在尝试向React组件添加功能-创建按钮的键盘快捷方式,该快捷方式在被触发时将播放音频。但是,代码在执行“ chooseButton”函数时不会执行嵌套的侦听器,该监听器假定调用“ bindButton”。

class MediaButton extends React.Component {
constructor(props) {
    super(props);
    this.audio = new Audio();
    this.playSample = this.playSample.bind(this);
    this.handleClick = this.handleClick.bind(this);
    this.chooseButton = this.chooseButton.bind(this);
    this.state = { playing: false };
    this.audio.onended = () => {
        this.setState({ playing: false });
    }

}

handleClick(e) {
    if (e.altKey) {
        this.chooseButton();
    }
    else {
        this.playSample();
    }
}


chooseButton() {
    function bindButton(e) {
        console.log('starting to bind');
        const key = e.keyCode;
        document.addEventListener(onkeydown, e => {
            if (e.keyCode === key) {
                this.playSample();
            }
            document.removeEventListener(onkeydown, bindButton, false);
            console.log('Done');
        }, false)
    }
    document.addEventListener(onkeydown, bindButton, false);
    console.log('Click button you want to assign to sample');
}

playSample() {
        this.audio.play();
        this.audio.onplay = () => {
            this.setState({playing: true});
        }
}

render() {
    return (
        <button onClick={this.handleClick}></button>
    )
}

}

0 个答案:

没有答案