[英]typescript react, dynamic props based on a certain prop value?
我正在尝试创建一个 React 组件,该组件可以具有基于某个道具值的动态道具,但我停留在类型声明中......
const layerMap = {
l1: {
text: 'l1 text'
},
l2: {
image: 'l2 image'
}
};
type ElProps<T, K extends keyof T, NK extends keyof T[K]> = {
layerName: K;
[P in NK]: T[K][NK];
/* ^^^^^^^^^
A computed property name in a type literal must refer to an expression whose type is a literal type or a 'unique symbol' type.ts(1170)
A computed property name must be of type 'string', 'number', 'symbol', or 'any'.ts(2464)
*/
};
function Elem<
L extends typeof layerMap,
LKey extends keyof L,
LPKey extends keyof L[LKey]
>(props: ElProps<L, LKey, LPKey>) {
return <h1>element</h1>;
}
我的目标是让组件Elem
可以这样使用,根据传递的layerName
的值生成动态道具
/*
when layerName is `l1`, Elem's props will be { layerName: string, text: string; }
when layerName is `l2`, Elem's props will be { layerName: string, image: string; }
*/
const App = (props: any) => (
<div>
<Elem layerName="l1" text="text" />
<Elem layerName="l2" image="image" />
</div>
)
我终于弄清楚了,通过使用交集类型( &
运算符)
import React from "react";
const layerMap = {
l1: {
text: 'l1 text'
},
l2: {
image: 'l2 image'
}
};
type ElProps<T, K extends keyof T, NK extends keyof T[K]> = {
[P in NK]?: T[K][NK];
} & { layerName: K };
function Elem<
L extends typeof layerMap,
LKey extends keyof L,
LPKey extends keyof L[LKey]
>(props: ElProps<L, LKey, LPKey>) {
return <h1>element {props.layerName}</h1>;
}
function App() {
return (<>
<Elem layerName="l1" text="x" />
<Elem layerName="l2" image="x" />
</>);
}
export default App;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.