仅使用 ReactJS 专注于自定义模态

Focus on custom modal only using ReactJS

我是 ReactJS 的新手,在某些事情上卡住了。

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

我不能为此使用 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组件的构造函数中。不然好像不行。

希望对您有所帮助。