React无法专注于div

Ani*_*ail 8 reactjs

当我点击这里的按钮时,我正在尝试专注于div .我把我的问题减少到下面的代码,虽然在div对象上调用焦点,但从不调用onFocus.也autoFocus没有解决我的问题,因为我希望能够在组件安装后多次更改焦点.

class App extends React.Component {
    constructor() {
        super();
        this.my_refs = {};
        this.focusByID.bind(this);
    }

    focusByID(id){
        let myRef = this.my_refs[id];
        if(myRef){
            console.log('focusing on ', id, myRef);
            myRef.focus();
        }
    }
    render() {
        return (
            <div>
                <div
                    id="bigRedDiv"
                    style={{height : 200, width : 200, backgroundColor : 'red'}}
                    ref={(input) => this.my_refs['bigRedDiv'] = input }
                    onFocus={() => console.log('FOCUS IS ON BIG RED DIV')}
                    onClick={() => this.focusByID('bigRedDiv')}
                >
                </div>
            </div>
        );
    }
}
Run Code Online (Sandbox Code Playgroud)

这是一个包含此代码的小提琴.

And*_*rew 10

只是:

...
<div 
    tabIndex="0" //use this attribute
    id="bigRedDiv" 
    style={{height : 200, width : 200, backgroundColor : 'red'}} 
    ref={(input)=> this.my_refs['bigRedDiv'] = input } 
    onFocus={() => console.log('FOCUS IS ON BIG RED DIV')} 
    onClick={() => this.focusByID('bigRedDiv')} >
</div>
...
Run Code Online (Sandbox Code Playgroud)

  • 谢谢 !事实上,正如我刚刚了解到的那样,tabindex="0" 允许除链接和表单元素之外的元素接收键盘焦点。 (3认同)