gpt4 book ai didi

javascript - React Functional Component + TypeScript 函数重载怎么写?

转载 作者:搜寻专家 更新时间:2023-10-30 21:25:42 28 4
gpt4 key购买 nike

我知道如何编写 React 函数式组件和 TypeScript + 函数重载。

但是当这两个结合在一起的时候,我就糊涂了!

这里是一个最小的代码示例来说明我想做什么:

import React, { FunctionComponent } from 'react';

type PropType1 = { type: 'type1'; name: string };
type PropType2 = { type: 'type2'; age: number };

// How do I properly hook FunctionComponent + PropType1 + PropType2?
// It's called FunctionComponent right?

function Example({ type, name, age }) {
if (name === undefined) {
return (
<div>
{type}, {age}
</div>
);
} else {
return (
<div>
{type}, {name}
</div>
);
}
}


export default Example

这个例子的用法应该是这样的:

<Example type="type1" name="Joseph"/>
// => <div> type1, Joseph </div>

<Example type="type2" age={18}/>
// => <div> type2, 18 </div>

<Example type="type3" name="Joseph" age={18}/>
// => Compile Error!

如何正确 Hook FunctionComponent + PropType1 + PropType2?

而且,它叫做 FunctionComponent 对吧?

最佳答案

你可以试试Union Types并检查组件中的 Prop 类型。

import React, { FunctionComponent } from 'react';

type PropType1 = { type: 'type1'; name: string };
type PropType2 = { type: 'type2'; age: number };

function Example(props: PropType1 | PropType2) {
if (props.type === 'type1') {
return (
<div>
{props.type}, {props.name}
</div>
);
} else {
return (
<div>
{props.type}, {props.age}
</div>
);
}
}

export default Example;

用法

<Example type="type1" name="Joseph"/>
// => <div> type1, Joseph </div>

<Example type="type2" age={18}/>
// => <div> type2, 18 </div>

<Example type="type3" name="Joseph" age={18}/>
// => Compile Error: Type '"type3"' is not assignable to type '"type1" | "type2"'

<Example type="type1" age={18}/>
// => Compile Error

Demo

关于javascript - React Functional Component + TypeScript 函数重载怎么写?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56213809/

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