【发布时间】:2022-01-18 05:45:05
【问题描述】:
我需要为我的组件输入 HOC(这被问了数百万次)。但我需要做一些与典型的 withSomething 注入相反的事情。我需要向我的外部组件添加一个额外的属性,并将所有其他(但未知的)属性传递给内部组件:
// @flow
import * as React from 'react'
// That's an example of a standard component doing nothing
type Props = {| str: string, num: number |}
const Hello = ({ str, num }: Props): React.Node => {
console.log(str, num)
return <div>'Hello'</div>
}
// That's the standard (and working) example of the component with injected prop.
// It's an equivalent of prop currying, I set str prop to some default value
type InnerInjected = {| str: string |}
const withInnerInject = <P>(
Component: React.AbstractComponent<$Exact<{ ...P, ...InnerInjected }>>,
): React.AbstractComponent<P> => {
return (props: P) => {
return <Component str="aaa" {...props} />
}
}
const InnerInjectHello = withInnerInject(Hello)
// And here is non-working example.
export const withOuterInject = <P>(
Component: React.AbstractComponent<P>,
): React.AbstractComponent<P> => {
return (props: P) => {
// I need to pass the bool (or some other variable) to my component to perform
// some action with it based on its value and return the standard component with all
// that component properties that I don't know yet.
const { bool, ...rest } = props
return <Component {...rest} />
}
}
const OuterInjectHello = withOuterInject(Hello)
const Example = (): React.Node => {
return (
<>
{/* Both num and str props are set as intended */}
<Hello num={25} str="something" >
{/* str is injected with value of 'aaa' */}
<InnerInjectHello num={25} />
{/* Works, but typing is wrong */}
<OuterInjectHello str="aa" num={25} bool />
</>
)
}
我尝试了几种 $Diff 和 $Rest 方法,但它们根本不适用于泛型。
【问题讨论】:
标签: javascript reactjs typescript flowtype