只使用ReactJS关注自定义模态

Focus on custom modal only using ReactJS

本文关键字:自定义 模态 ReactJS      更新时间:2024-06-13

我是ReactJS的新手,在某些方面遇到了困难。

我有一个自定义模式,点击按钮就会弹出。此模式包含2个其他按钮。当我开始按下选项卡按钮时出现问题。:(焦点移动到模态屏幕后面,用户可以与应用程序交互,这是一个严格的no!

我不能对这个使用React模态。

有没有一种方法可以使用ReactJS/Javascript使焦点停留在顶部的模态div上。到目前为止,我已经尝试了以下方法,但似乎效果不佳。

请看一看。如有任何帮助,我们将不胜感激。

    _focusRestrict() {
    document.addEventListener('keydown', event => {
        if (this.state.resetLifePlanner) {
            //alert('Called');
            event.stopPropagation();
            const key = (event.keyCode ? event.keyCode : event.which);
            switch (key) {
            case 9:
                if (document.activeElement.id === 'confirmButton') {
                    console.log('Called if:: move focus to cancelButton');
                    this.cancelButton.focus();
                    //React.findDOMNode(this.refs.cancelButton).focus();
                    //document.getElementById('cancelButton').focus();
                }
                else if (document.activeElement.id === 'cancelButton') {
                    console.log('Called else:: move focus to confirmButton');
                    this.confirmButton.focus();
                    //React.findDOMNode(this.refs.confirmButton).focus();
                    //document.getElementById('confirmButton').focus();
                }
            }
        }
    }, true);
}
componentDidMount() {
    this._focusRestrict();
}

是否有ReactJS事件处理方式?

此外,有没有一种方法可以将事件绑定到div?

event.stopPropagation();之后,只需添加event.preventDefault();

在卸载模态组件时,不要忘记删除侦听器。您必须将当前的匿名函数放置在命名函数中。

export default class ArtistList extends Component {
    // ...
    componentDidMount() {
        document.addEventListener('keydown', handleKeydown, true);
    }
    componentWillunmount() {
        document.removeEventListener('keydown', handleKeydown);
    }
}

function handleKeydown(e) {
    if (this.state.resetLifePlanner) {
        //alert('Called');
        event.stopPropagation();
        event.preventDefault();
        const key = (event.keyCode ? event.keyCode : event.which);
        switch (key) {
        case 9:
            if (document.activeElement.id === 'confirmButton') {
                console.log('Called if:: move focus to cancelButton');
                this.cancelButton.focus();
                //React.findDOMNode(this.refs.cancelButton).focus();
                //document.getElementById('cancelButton').focus();
            }
            else if (document.activeElement.id === 'cancelButton') {
                console.log('Called else:: move focus to confirmButton');
                this.confirmButton.focus();
                //React.findDOMNode(this.refs.confirmButton).focus();
                //document.getElementById('confirmButton').focus();
            }
        }
    }
}

上面的答案是正确的。但我们也需要添加

    // This is needed to properly add and remove the keydown event listener
    this._restrictFocus = _.bind(this._restrictFocus, this);

在react组件的构造函数中。否则,它似乎不起作用。

希望这能有所帮助。