我正在做一个HOC(高阶组件),这有助于条件渲染。
代码如下所示:
interface ConditionalProps {
renderIf?: boolean
}
const ConditionalizeComponent = <Props,>(
OriginalComponent: FC<Props>
): FC<Props & ConditionalProps> => {
return (props) => {
return <OriginalComponent {...props} />
}
}
interface TestComponentProps
extends DetailedHTMLProps<
HTMLAttributes<HTMLParagraphElement>,
HTMLParagraphElement
> {}
function BBB() {
const TestComponent: FC<TestComponentProps> = ConditionalizeComponent(
(props) => <p {...props} />
)
return <TestComponent renderIf={true} />
}
这个代码看起来工作得很完美
现在我想将收到的任何ref转发到OriginalComponent
,为此我使用react函数forwardRef()
。
下面的代码与上面的代码相同,但不是在末尾返回一个正则函数(正则函数=我的意思是函数组件),而是返回一个forwardRef:
interface ConditionalProps {
renderIf?: boolean
}
const ConditionalizeComponent = <Props,>(
OriginalComponent: FC<Props>
): FC<Props & ConditionalProps> => {
return forwardRef((props, ref) => {
return <OriginalComponent {...props} ref={ref} />
})
}
interface TestComponentProps
extends DetailedHTMLProps<
HTMLAttributes<HTMLParagraphElement>,
HTMLParagraphElement
> {}
function BBB() {
const TestComponent: FC<TestComponentProps> = ConditionalizeComponent(
(props) => <p {...props} />
)
return <TestComponent renderIf={true} />
}
然而,Typescript不喜欢这样,它正在抱怨,并指出以下***非常***长的错误:
Type 'ForwardRefExoticComponent<PropsWithoutRef<Props & ConditionalProps> & RefAttributes<unknown>>' is not assignable to type 'FC<Props & ConditionalProps>'.
Types of property 'propTypes' are incompatible.
Type 'WeakValidationMap<PropsWithoutRef<Props & ConditionalProps> & RefAttributes<unknown>> | undefined' is not assignable to type 'WeakValidationMap<Props & ConditionalProps> | undefined'.
Type 'WeakValidationMap<PropsWithoutRef<Props & ConditionalProps> & RefAttributes<unknown>>' is not assignable to type 'WeakValidationMap<Props & ConditionalProps>'.
Type 'keyof Props | "renderIf"' is not assignable to type 'keyof PropsWithoutRef<Props & ConditionalProps> | keyof RefAttributes<unknown>'.
Type 'keyof Props' is not assignable to type 'keyof PropsWithoutRef<Props & ConditionalProps> | keyof RefAttributes<unknown>'.
Type 'string | number | symbol' is not assignable to type 'keyof PropsWithoutRef<Props & ConditionalProps> | keyof RefAttributes<unknown>'.
Type 'string' is not assignable to type 'keyof PropsWithoutRef<Props & ConditionalProps> | keyof RefAttributes<unknown>'.ts(2322)
我想知道,我的代码出了什么问题,或者forwardRef的返回类型是什么,或者如何使用它。
1条答案
按热度按时间9rnv2umw1#
React forwardRef是一个允许父组件将引用向下传递(即“转发”)给其子组件的方法。在React中使用forwardRef为子组件提供了一个对父组件创建的DOM元素的引用。然后,这允许子组件在使用该元素的任何地方读取和修改该元素