简体   繁体   English

使用打字稿为键选择通用类型

[英]React select generic type for key with typescript

I have the following component that wraps a Material UI select:我有以下组件来包装 Material UI 选择:

  return (
    <Box display="flex" justifyContent={justifyContent}>
      <SortWrapper>
        <InputLabel htmlFor={id} shrink={true} >
          Sort by
        </InputLabel>
        <Select
          data-bdd={id}
          id={id}
          defaultValue={defaultSortOrder}
          onChange={handleChangeSort}
        >
          {options.map((f: any) => (
            <MenuItem key={f.sortableKey} value={f.sortableKey}>
              {f.displayName}
            </MenuItem>
          ))}
        </Select>
      </SortWrapper>
    </Box>
  )

and than I use it like so inside the UI:然后我在 UI 中像这样使用它:

...
              <SelectInput
                defaultSortOrder={defaultSortOrder}
                handleChangeSortOrder={handleChangeSortOrder}
                style={selectInputStyle}
                id="repairs-search-sort"
                options={sortableFields}
              />
...

and sortableFields is like so:和 sortableFields 是这样的:

sortableFields: SortableField[]

the key and value are too tight to SortableField[]键和值对SortableField[]来说太紧了

export default class SortableField {
  public displayName: string = ''
  public sortableKey: string = ''
}

is there a way to make key and value values more generic?有没有办法让keyvalue值更通用?

Like <MenuItem key={ket} value={value}> regardless of the type we are consuming in the UI?<MenuItem key={ket} value={value}>而不是我们在 UI 中使用的类型?

There's a couple techniques you can use, which I've seen in various third-party libraries:您可以使用几种技术,我在各种第三方库中都看到过这些技术:

  1. Define labelKey and valueKey props.定义labelKeyvalueKey道具。 This will let you define which properties to search for.这将让您定义要搜索的属性。
interface MyInterface1 {
  id: string;
  name: string;
}

interface MyInterface2 {
  key: {
    id: string,
    description: string
  };
}

<SelectInput<MyInterface1> labelKey="id" valueKey="name"/>

<SelectInput<MyInterface2> labelKey="key.id" valueKey="key.description"/>
  1. Expose a callback to return the label and values.公开回调以返回标签和值。 Sometimes you need to grab data outside of the options array, or perform some formatting (Dates, Times, Composite labels).有时您需要获取options数组之外的数据,或执行一些格式化(日期、时间、复合标签)。
interface MyInterface1 {
  id: string;
  firstName: string;
  lastName: string;
  email: string;
}

function buildLabel(option: MyInterface1): string {
  return `${option.firstName} ${option.lastName}`;
}

<SelectInput<MyInterface1> labelCallback="buildLabel" valueKey="id"/>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM