【问题标题】:typescript react, dynamic props based on a certain prop value?打字稿反应,基于某个道具值的动态道具?
【发布时间】:2021-05-10 11:01:51
【问题描述】:

我正在尝试创建一个 React 组件,它可以基于某个 prop 值具有动态 props,但我卡在了类型声明中......

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的值生成动态props

/* 

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>
)

【问题讨论】:

    标签: reactjs typescript


    【解决方案1】:

    我终于弄明白了,通过使用交集类型(&amp; 运算符)

    ts playground demo

    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;
    

    【讨论】:

      猜你喜欢
      • 2016-08-13
      • 2022-06-24
      • 2018-10-26
      • 1970-01-01
      • 2022-01-22
      • 1970-01-01
      • 1970-01-01
      • 2020-08-21
      • 1970-01-01
      相关资源
      最近更新 更多