React TS中RefObject类型不兼容与Hook规则报错的解决方案咨询
解决TS类型错误与React Hook规则冲突问题
问题根源
- 类型错误:
React.RefObject<HTMLDivElement | undefined>要求是一个包含current属性的对象,不能直接赋值undefined。 - ESLint错误:React Hook(比如
useRef)只能在**React函数组件(首字母大写)或自定义Hook(以use开头)**中调用,普通函数里调用会违反规则。
解决方案
方案1:手动构造合法的RefObject对象
直接创建一个符合RefObject类型结构的对象,无需调用useRef,完美避开Hook规则:
interface CommandProps { otherStuff: string; commandContainerRef: React.RefObject<HTMLDivElement | undefined>; } const getComponentProps = (): CommandProps => { return { otherStuff: 'stuff', // 手动构造RefObject,current设为undefined满足类型要求 commandContainerRef: { current: undefined }, }; };
方案2:将函数改为自定义Hook
如果这个函数的作用是为组件提供props,可以把它改成自定义Hook(函数名以use开头),这样就能合法调用useRef:
interface CommandProps { otherStuff: string; commandContainerRef: React.RefObject<HTMLDivElement | undefined>; } // 自定义Hook以use开头,符合React Hook规则 const useComponentProps = (): CommandProps => { const commandContainerRef = React.useRef<HTMLDivElement | undefined>(undefined); return { otherStuff: 'stuff', commandContainerRef, }; };
之后在组件中调用这个Hook即可:
const MyComponent = () => { const props = useComponentProps(); // ... };
方案3:调整类型定义(备选)
如果业务允许commandContainerRef为undefined,可以修改接口类型,允许两种值:
interface CommandProps { otherStuff: string; // 允许RefObject或undefined commandContainerRef: React.RefObject<HTMLDivElement | undefined> | undefined; } const getComponentProps = (): CommandProps => { return { otherStuff: 'stuff', commandContainerRef: undefined, }; };
注意:这个方案会放宽类型约束,仅在业务场景允许时使用。
内容的提问来源于stack exchange,提问作者flyingbee
相关产品推荐
相关产品推荐

