簡體   English   中英

Flow React HOC 類型(無 HOC)

[英]Flow React HOC typing (without HOC)

我需要為我的組件輸入 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<> 方法,但它們根本不適用於 generics。

我最終得到了這樣的結果:

import { Component as _Component } from 'package'

type InjectedProps = {|
  newProp: boolean,
|}

export const Component = <P>(props: $Exact<{...InjectedProps, ...P}>) => {
  const { newProp, ...rest } = props
  
  // doSomething with newProp
  return <_Component {...rest} />
}

可能,這就足夠了,我不需要在這里特設。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM