简体   繁体   中英

How can I focus on an element within an imported React component?

I'm importing React-Search-Input and would like to programmatically focus on the text input contained within the component, but it contains no refs and no method to focus on the input.

So because of that, running .focus() on the element, doesn't focus on what I need, which is the text input within the component. It instead focuses on a container element.

Do I have any options here besides forking the project? Thanks!

You can use ReactDOM.findDOMNode to retrieve the element and then call focus on the first child. Something like this:

componentDidMount() {
    ReactDOM.findDOMNode(this.searchInput).firstChild.focus();
}

and then render...

<SearchInput
    className="search-input"
    onChange={this.searchUpdated}
    ref={(ref) => this.searchInput = ref}
/>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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