reactjs - 如何将焦点设置在组件 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>
);
}; 导出默认详细信息;
解决方案
我们autoFocus
在 React 中有 prop,所以你可以试试<h4 autoFocus />
.
但是你也可以用 ref 解决这个问题:
const h4 = useRef()
useEffec(() =>
h4.current.focus()
)[];
return( <h4 ref={h4} /> )
您是对的,可能需要 tabIndex(在 React 中使用驼峰式大小写)才能使其适用于 h4 元素。
推荐阅读
- google-bigquery - Google CLI 未创建 Transfer Service 且未显示详细错误
- vba - PPT VBA,将所有打开的PPT另存为PDF
- networking - 智能手机中的数据链路层和物理层设备
- wso2 - 无法在 WSO2 API Manager 3.1.0 中启用 MailtoSender
- reactjs - 如何在另一个组件中使用一个组件的状态?独立组件(React)
- karate - 如何删除空手道中的多个数组对象?
- c++ - 将错误记录到 rsyslog 数据库会给出不正确的优先级枚举
- mysql - 这是应该使用窗口功能的情况吗?
- javascript - C3js:单个数据中的多色线
- scrapy - 自定义中间件导致重复过滤器过滤掉所有请求