[英]How to handle "useRef()" type in a custom React component have written with typescript
I want useing "useRef()" in my component as an input selector value to be able to handle a filter.我想在我的组件中使用“useRef()”作为输入选择器值,以便能够处理过滤器。 but I got an error on ref={selectedMonth} && ref={selectedYear} :
但我在 ref={selectedMonth} && ref={selectedYear} 上遇到错误:
import styles from "./event-search.module.css";
import {
DetailedHTMLProps,
FormHTMLAttributes,
useEffect,
useRef,
} from "react";
import { LinkButton } from "../../ui/button/Button";
export const EventSearch: React.FunctionComponent<
DetailedHTMLProps<FormHTMLAttributes<HTMLFormElement>, HTMLFormElement> & {}
> = ({ ...rest }) => {
// useEffect({}, []);
const selectedYear = useRef<HTMLDivElement>(null);
const selectedMonth = useRef<HTMLDivElement>(null);
return (
<form {...rest} className={styles.form}>
<div className={styles.controls}>
<div className={styles.control}>
<label htmlFor="year">Year</label>
<select id="year" ref={selectedYear}>
<option value="2021">2021</option>
<option value="2022">2022</option>
</select>
</div>
<div className={styles.control}>
<label htmlFor="month">Month</label>
<select id="month" ref={selectedMonth}>
// Type 'RefObject<HTMLDivElement>' is not assignable to type
//'LegacyRef<HTMLSelectElement> | undefined'.
// Type 'RefObject<HTMLDivElement>' is not assignable to type
//'RefObject<HTMLSelectElement>'.
// Type 'HTMLDivElement' is missing the following properties from type
// 'HTMLSelectElement': autocomplete, disabled, form, labels, and 20 more.
<option value="1">January</option>
<option value="2">February</option>
<option value="3">March</option>
<option value="4">April</option>
<option value="5">May</option>
<option value="6">June</option>
<option value="7">July</option>
<option value="8">August</option>
<option value="9">September</option>
<option value="10">October</option>
<option value="11">November</option>
<option value="12">December</option>
</select>
</div>
</div>
<LinkButton
className="some"
onClickFunc={() => alert("Hello")}
title="Find Events"
/>
</form>
);
};
export default EventSearch;
and if you think I need to change the whole type handling in my component plz give your best Idea如果您认为我需要更改组件中的整个类型处理,请提供您最好的想法
您尝试添加 ref 的元素是 HTMLSelectElements 而不是 HTMLDivElements,您应该将 useRef 函数上的类型更改为
let ref = useRef<HTMLSelectElement>(null);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.