[英]pass an array of objects to a dropdown (select) using typescript
I'm trying to pass this array of objects我正在尝试传递这个对象数组
options = [
{label:'React', value: 'react'},
{label:'ReactNative', value: 'react-native'},
{label:'JavaScript', value: 'js'},
{label:'CSS', value: 'css'}
];
to a select component到 select 组件
<CustomSelect options={options} />
Nothing is taking the curly braces away.没有什么能把花括号拿走。 I've tried:
我试过了:
let options: { label: string, value: string}[] = [
{label:'React', value: 'react'},
{label:'ReactNative', value: 'react-native'},
{label:'JavaScript', value: 'js'},
{label:'CSS', value: 'css'}
];
this is a type array with strings in it.这是一个包含字符串的类型数组。
I've also tried:我也试过:
interface Option {
label: string,
value: string
}
let options: Option[] ;
options = [
{label:'React', value: 'react'},
{label:'ReactNative', value: 'react-native'},
{label:'JavaScript', value: 'js'},
{label:'CSS', value: 'css'}
];
to create an object with strings in it.创建一个带有字符串的 object。 My understanding is that I create an interface or a type to create an object?
我的理解是我创建一个接口或者类型创建一个object? Once I create an object, I need to define the array of strings and I don't know how to do that correctly in a typescript way.
创建 object 后,我需要定义字符串数组,但我不知道如何以 typescript 的方式正确执行此操作。
If I understand correctly from the question, you might need something like the following:如果我从问题中理解正确,您可能需要以下内容:
<select>
<option value="">Select</option>
{options.map((options) => (
<option key={options.label} value={options.value}>
{options.label}
</option>
))}
</select>
If you want to make a custom dropdown component in typescript, this codesandbox might help如果你想在 typescript 中制作自定义下拉组件,这个 codesandbox 可能会有所帮助
https://codesandbox.io/s/determined-rhodes-n6i8lc https://codesandbox.io/s/determined-rhodes-n6i8lc
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.