[英]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
元素創建一個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.