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

大兔子大兔子 提交于 2020-04-17 21:30:33

问题


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

回答1:


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




回答2:


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




回答3:


For function component you can use hooks, You can use useEffect it is work as ComponentDidMount for functional component.For more detail go through this link : https://reactjs.org/docs/hooks-state.html



来源:https://stackoverflow.com/questions/57200730/react-way-of-setting-focus-on-a-particular-button-in-functional-component

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!