首页 > 解决方案 > 如何将焦点设置在组件 html 标记上

问题描述

我需要在加载时将焦点设置在我的功能组件中的标签上。我不能让它正常工作。请帮忙!以下是我的代码;细节.js

import React,{useState,useEffect} from 'react';
const Detail=({course})=>{
const [myfocus]=useState(null);
useEffect(() => {
    setState({
    this.myfocus.focus(); //? how to set id myfocus to this.myfocus.focus()
  });

return (
   <div>
    <h4  tabindex="0"   id="myfocus">
     {course.SUBJECT} {course.CATALOG_NBR}
     </h4>

</div>
);

}; 导出默认详细信息;

标签: reactjs

解决方案


我们autoFocus在 React 中有 prop,所以你可以试试<h4 autoFocus />.

但是你也可以用 ref 解决这个问题:

const h4 = useRef()

useEffec(() => 
    h4.current.focus()
)[];

return( <h4 ref={h4} /> )

您是对的,可能需要 tabIndex(在 React 中使用驼峰式大小写)才能使其适用于 h4 元素。


推荐阅读