I read similar questions but I think my situation is a little bit different. First of all, I am using React 15 and I have two components (parent and child).
I reach the input element in a plain JavaScript way and focus on it in componentDidUpdate, however, componentDidMount doesn't work. When I log out the element, I can see the correct element in the console.
Parent Component
componentDidMount(){
console.log(document.getElementById('abc')) // logs the correct element
document.getElementById('abc').focus(); // DOES NOT work
}
componentDidUpdate(){
document.getElementById('abc').focus(); // works
}
Child Component
<input autofocus={true} name="search" id="abc" type="text"></input>
Maybe try using ref
Your Parent Component:
componentDidMount() {
this.input.focus()
}
<ChildComponent inputRef={node => (this.input = node)} />
Your Child Component:
const ChildComponent = ({ inputRef }) => (
<input name="search" ref={inputRef} type="text"/>
)
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.