在 React 组件 Props 中使用通用流类型并实例化通用组件>

Use Generic flow types in React component Props and instantiate generic component>

我在 google.

上遇到了 Flow generics vs React Components 问题,我一直无法找到答案

我想用带有通用参数的道具制作一个通用组件,并在 render() 方法中实例化它。到目前为止运气不好 - 我的最小示例代码在这里:

Try it out

import React from 'react'


// Different commands for different contexts
type PaymentCommands = 'pay' | 'reject' | 'unused'
type CartCommands = 'checkout' | 'empty'


type Command<CommandType> = {
  userId: string,
  command: CommandType,
}

// Props let the component take different types of commands
type Props<CommandType> = {
  commands: Command<CommandType>[]
}


// The CommandButtons component should be used for sending various commands depending on context.
class CommandButtons<CommandType> extends React.Component<Props<CommandType>> {
  render() {
    return (
      <div>
        BLABLA
      </div>
    )
  }
}

// But no luck in instantiating a specific type of the CommandButtons generic, so far
const PaymentCommandButtons = () =>  {return CommandButtons<PaymentCommands>}

type PaymentContainerProps = { userId: string }
class PaymentContainer extends React.Component<PaymentContainerProps> {
  render() {
//      return (
//          <div><CommandButtons<PaymentCommands> commands={[{userId: 1, commmand: 'pay'}, {userId:2, command: 'reject'}]} /></div>
//        )
    return (
       <div><PaymentCommandButtons commands={ [{userId: 1, commmand: 'pay'}, {userId:2, command: 'reject'}] } /></div>
    )
  }
}

我是这样解决的!

const PaymentCommandButtons = (props: Props<PaymentCommands>) => <CommandButtons { ...props } />