reactjs - 打字稿反应,基于某个道具值的动态道具?
问题描述
我正在尝试创建一个 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;
推荐阅读
- matplotlib - 这种类型的情节叫什么?
- regex - 匹配线的正则表达式
- api - Juriscraper REST API 的日期范围格式是什么?
- javascript - Jquery按属性部分值查找元素
- date - 日期的幂双减法
- python - Python selenium # Chrome 扩展 - waspinspector-analytics: 打开 waspinspector 页面而不是 driver.get(url)
- html - 如何在 Laravel 中将 href 转换为提交按钮
- c++ - C ++动态数组不分配内存
- amazon-web-services - 使用 CloudFlare + AWS Application LoadBalancer 出现错误 522
- java - 日期为 x 标签的 JFreeChart