简体   繁体   中英

react way of setting focus on a particular button in functional component?

Hi I am new to react and on my page load i need to give focus to a button. I am using functional component. I had seen example with class component and in that using componentDidMount and setting focus using refs.

Here i am using functional component and no ComponentDidMount as well.. How can i set focus on functional component to a button on page load ?

export const SubPageHeader=({prop})=>{
return(
<div>
<input type="button"/>
}
export default SubPageHeader

You can make use of useEffect hook which is equivalent to componentDidMount ,

const SubPageHeader=({prop})=>{
  let textInput = null;
  useEffect(()=>{
    textInput.focus();
  })
  return(
    <div>
      <input type="button" value="Button" ref={(button) => { textInput = button; }}/>
    </div>
  )
}

Demo

you can use useEffect instead of componentDidMount to do same thing in functional component.

Use ref on your button element and use it in useEffect method of react to focus button element

对于功能组件,您可以使用钩子,可以使用useEffect作为功能组件的ComponentDidMount。有关更多详细信息,请访问此链接: https ://reactjs.org/docs/hooks-state.html

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