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

时间:2018-06-12 13:05:48

标签: reactjs flowtype react-props

我有一个Flow generics vs React Components问题,我无法在google上找到答案。

我想创建一个带有泛型参数的道具的通用组件,并在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>
    )
  }
}

1 个答案:

答案 0 :(得分:1)

我这样解决了!

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