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



我有一个 Flow 泛型与 React 组件的问题,我无法在谷歌上找到答案。

我想用接受泛型参数的 props 制作一个通用组件,并在 render(( 方法中实例化它。到目前为止没有运气 - 我的最小示例代码在这里:

试试看

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 } />

最新更新