简体   繁体   中英

focus works in componentDidUpdate but not in componentDidMount

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.

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