反应将焦点设置在功能组件中的特定按钮上的方式? [英] react way of setting focus on a particular button in functional component?

查看:48
本文介绍了反应将焦点设置在功能组件中的特定按钮上的方式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是新来的人,在我的页面加载中,我需要将重点放在按钮上.我正在使用功能组件.我看过类组件的示例,其中使用componentDidMount并使用引用设置焦点.

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.

这里我使用的是功能组件,也没有使用ComponentDidMount.如何在页面加载时将功能组件的焦点设置为按钮?

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

推荐答案

您可以使用 useEffect 钩子,该钩子等效于 componentDidMount

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>
  )
}

演示

这篇关于反应将焦点设置在功能组件中的特定按钮上的方式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆