[英]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?有没有办法让
key
和value
值更通用?
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:您可以使用几种技术,我在各种第三方库中都看到过这些技术:
labelKey
and valueKey
props.labelKey
和valueKey
道具。 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"/>
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.