gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 14:18:42 25 4
gpt4 key购买 nike

我有一个 Flow generics 与 React Components 的问题,但我在 google 上找不到答案。

我想创建一个带有接受通用参数的 props 的通用组件,并在 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 } />

关于reactjs - 在React组件Props中使用通用流类型并实例化通用组件>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50817998/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com