我正在使用 Typescript 和 React。我为自定义函数创建了一个单独的文件 DivPosition.tsx
我使用 useRef 将 div 元素的引用传递给我的函数,但在传递参数时遇到错误。
const Home = () => {
const divRef = useRef<HTMLDivElement>(null);
const x = DivPosition(divRef);
return (
...
)
}
我的 DivPosition.tsx 代码:
interface IDivPosition{
divRef: HTMLDivElement | null
}
export const DivPosition = ({divRef}: IDivPosition) => {
useEffect(() => {
console.log(divRef);
});
...
return x;
};
我收到一条错误消息: “RefObject”类型的参数不可分配给“IDivPosition”类型的参数。 “RefObject”类型中缺少属性“divRef”,但“IDivPosition”类型中需要属性“divRef”
最佳答案
useRef
的返回值为RefObject
,类型定义
/*
* convenience overload for refs given as a ref prop as they typically start with a null value
*
* Usage note: if you need the result of useRef to be directly mutable, include `| null` in the type
* of the generic argument.
* @version 16.8.0
* @see https://reactjs.org/docs/hooks-reference.html#useref
*/
function useRef<T>(initialValue: T|null): RefObject<T>;
尝试:
import { useEffect, useRef } from 'react';
interface IDivPosition {
divRef: RefObject<HTMLDivElement>;
}
export const useDivPosition = ({ divRef }: IDivPosition) => {
useEffect(() => {
console.log(divRef);
});
return null;
};
const Home = () => {
const divRef = useRef<HTMLDivElement>(null);
const x = useDivPosition({ divRef });
return null;
};
软件包版本:
"react": "^16.14.0",
"@types/react": "^16.14.14",
"typescript": "^4.4.2"
此外,请以“use”开头的命名自定义 Hook 。
Do I have to name my custom Hooks starting with “use”? Please do. This convention is very important. Without it, we wouldn’t be able to automatically check for violations of rules of Hooks because we couldn’t tell if a certain function contains calls to Hooks inside of it.
关于reactjs - 类型 'RefObject<HTMLDivElement>' 的参数不可分配给类型 'IDivPosition' 的参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70504305/