本文介绍了相当于React.memo的Typescript通用类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有什么方法可以在React.memo中设置新的泛型吗?
Is there any way to set new generic in React.memo?
例如,对于类组件,我可以使用
For example, for class components, I can use
// set generic
class GenericClass<G extends string | number> extends PureComponent {}
// and use like this
<GenericClass<number> />
在以下情况下,我想使G型通用.
In the below scenario, I want to make type G generic.
type G = string;
const MemoComponent = memo<{ value: G; onValueChange: (newValue: G) => void }>(
({ value, onValueChange }) => {
return (
<select
onClick={() => {
// do calculation
onValueChange(value);
}}
>
Button
</button>
);
}
);
我想知道还有什么方法可以在React.memo中设置泛型吗?例如,如下所示
I want to know is there any way to set generic in React.memo too? For example, like below
const MemoComponent = <G extends string | number | object>React.memo<{value: G}>(({value}) => component)
// and use like this
<MemoComponent<number> />
推荐答案
我遇到了同样的问题,并以此解决.
I had the same issue and solved like this.
interface ISomeComponentWithGenericsProps<T> { value: T; }
function SomeComponentWithGenerics<T>(props: ISomeComponentWithGenericsProps<T>) {
return <span>{props.value}</span>;
}
export default React.memo(SomeComponentWithGenerics) as typeof SomeComponentWithGenerics;
这篇关于相当于React.memo的Typescript通用类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!