简体   繁体   English

React弹出窗口的Focus和tabIndex

[英]Focus and tabIndex for React popup

I have the following React popup component: 我有以下React弹出组件:

export class PopUp extends React.Component {
  public divContainer: HTMLElement;

  public componentDidMount() {
    this.divContainer.focus();
  }

  private buildRef = (e: HTMLDivElement) => {
    this.divContainer = e;
  }

  render() {
    return (
      <div ref={this.buildRef} tabIndex={0}>
        <header>My PopUp</header>
        <div>
          {this.props.children}
        </div>
      </div>
    );
  }
}

This is one of the ways it can be used: 这是可以使用它的方法之一:

<PopUp>
  <div>
    <textarea rows="4" cols="50">
      Stuff goes here
    </textarea>
  </div>
  <button>Add</button>
</PopUp>

Right now when I tab, the focus gets put on the popup's parent div, as expected. 现在,当我按Tab键时,焦点将按预期放到弹出窗口的父div上。 If I keep tabbing, it focuses on the children but once the last child element is reached, the focus moves to the parent page on top of which the popup is opened. 如果我继续进行制表,它将重点放在children上,但是一旦到达最后一个child元素,焦点就会移到父页面上,在该父页面上将打开弹出窗口。

I only want tabbing/focusing to be restricted to the Pop up elements. 我只希望将制表/聚焦局限于“弹出”元素。 How can I get it to loop back to put focus on the popup's parent div once it's done focusing on the last child? 一旦完成对最后一个孩子的关注,我如何才能使它循环返回以将焦点放在弹出窗口的父div上?

I am hoping you resolved your issue already. 我希望您已经解决了您的问题。 But the way I have made a Dialog or popup with children component "loop" the tabbing, I had to add a blur={() => {this.theFirstChildReference.focus();}} 但是我制作带有子组件的“对话框”或“弹出”选项卡的方式是,我不得不添加blur = {()=> {this.theFirstChildReference.focus();}}

Today I typically put that in its own function of the class. 今天,我通常将其放在班级自身的功能中。 So 所以

setFirstChildFocus = () => {
  this.firstChildReference.focus();
};

and therefore 因此

blur={this.setFirstChildFocus}

property in the last Child component. 最后一个子组件中的属性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM