React 无法专注于 div

React unable to focus on div

提问人:Anis Smail 提问时间:7/31/2017 最后编辑:Anis Smail 更新时间:7/31/2017 访问量:7642

问:

当我单击像这里这样的按钮时,我试图专注于 div。我将问题简化为下面的代码,尽管 focus 被调用到 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>
        );
    }
}

下面是一个包含此代码的小提琴

反应JS

评论


答:

16赞 Andrii Starusiev 7/31/2017 #1

只:

...
<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>
...

评论

3赞 Anis Smail 8/1/2017
谢谢!事实上,tabindex=“0” 允许链接和表单元素以外的元素接收键盘焦点,正如我刚刚学到的那样。
0赞 Vladimir Jovanović 7/7/2020
谢谢!不知道这个。
0赞 Shahin Dohan 10/22/2023
将 tabIndex 设置为 -1 不是更好吗?tabindex= “-1” 从导航序列中删除元素,但可以使用 JavaScript 使其可聚焦。