簡體   English   中英

如何在單擊按鈕時關注子元素組件?

[英]How to focus on child element component on a button click?

當我點擊模態按鈕時,我正在使用react-bootstrap並導入組件模態,彈出模態但我希望焦點在單擊打開模態按鈕時直接轉到模態內的輸入字段,這是我無法進行的實現

我已經嘗試將屬性作為autoFocus,並嘗試使用refs,但現在沒有成功。

子組件

 <Modal

    aria-labelledby="contained-modal-title-vcenter"
    centered
  >

    <Modal.Body>
      <h4>File Name</h4>
      <input autoFocus aria-label="File name entering field"  className="form-control mt-3" name="term" type="text"  />
    </Modal.Body>

  </Modal>

觸發孩子的父母

 <Button 
          variant="dark"
          onClick={() => {this.setState({ modalShow: true }); } }
        >
        popper
        </Button>

        <MyVerticallyCenteredModal
          show={this.state.modalShow}
          onHide={modalClose}
          saver= {this.saveDataImage}
        />

我希望焦點直接轉到模態中的輸入字段以獲得良好的可訪問性

您可以使用useRef這里提到: useRef文檔

在您想要聚焦的INPUT組件中,您應該添加屬性“autoFocus”,例如:

<input autoFocus id=... name=.../>

有關更多信息,請檢查: 在渲染后將焦點設置為輸入

我們可以為我們的input元素創建一個ref ,當安裝了input元素的組件安裝時,我們可以使用componentDidMount生命周期鈎子來聚焦我們的輸入。

class Input extends React.Component {
  constructor() {
    super();
    this.inputRef = React.createRef();
  }

  componentDidMount = () => {
    this.inputRef.current.focus();
  };

  render() {
    return <input ref={this.inputRef} type="text" />;
  }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM