问题
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