在react jsx中渲染typescript映射



我有map对象:

const myMap = new Map<number,string>([
[10, "text1"],
[15, "text2"],
[20, "text3"]
])

寻找如何在React JSX中迭代此地图的方法。提前谢谢你

let nodes: React.ReactNode[] = [];
myMap.forEach((value, key) => {
nodes.push(<your jsx>);
})
return nodes; // if you are in a component where you want to render

或者,如果您想更深入一点,您可以扩展Map类型以添加映射函数。

declare global {
interface Map<K, V> {
map<K, V, R>(
this: Map<K, V>,
callbackfn: (value: V, key: K, map: globalThis.Map<K, V>) => R,
thisArg?: any,
): R[];
}
}
Map.prototype.map = function <K, V, R>(
this: Map<K, V>,
callbackfn: (value: V, key: K, map: globalThis.Map<K, V>) => R,
thisArg?: any,
): R[] {
const arr: R[] = [];
this.forEach((value, key, map) => {
arr.push(callbackfn(value, key, map));
});
return arr;
};
const nodes = myMap.map((value, key) => <div>...</div>);

最新更新