所以我有以下组件,它是使用react-select创建的下拉列表。
import React from 'react'
import Select from 'react-select';
const options = [
{ value: 'chocolate', label: 'Chocolate' },
{ value: 'strawberry', label: 'Strawberry' },
{ value: 'vanilla', label: 'Vanilla' }
];
class MealsFilters extends React.Component {
constructor(props) {
super(props);
this.state = {
selectedOption: null,
};
}
handleChange = (selectedOption) => {
this.setState({ selectedOption });
console.log(`Option selected:`, selectedOption);
}
render() {
const { selectedOption } = this.state;
return (
<div className="container my-3">
<div className="row">
<div className="col-lg-4 col-md-6 col-sm-8">
<Select
isMulti
isSearchable
placeholder={"catégories"}
value={selectedOption}
onChange={this.handleChange}
options={options}
/>
</div>
</div>
</div>
)
}
}
export default MealsFilters;
options
变量是文档中的默认变量。我实际上需要用每个可用的餐食类别替换其值。
如您所见,要做到这一点,我需要创建一个包含value
和label
的对象数组。
此组件通过名为meals
的道具访问膳食类别,如下所示:
console.log(this.props.meals);
=> [{
id: 0,
name: spaghettis,
category: italian,
price: 5.99},
{
id: 1,
name: hamburger,
category: american,
price: 7.99},
{
etc.
}, {}]
如何利用this.props.meals
来获取options
对象数组?
编辑:多餐可以具有相同的类别,我需要每个类别在选项中仅出现一次。
答案 0 :(得分:1)
您可以执行以下操作:
options={this.props.meals.map(
({id, name})=>({value:id,label:name})
)}
您还可以使用redux connect创建一个容器,该容器将为您映射数据到下拉值
您可以通过以下方式按类别合并数据:
var items = [
{
id: 0,
name: 'spaghettis',
category: 'italian',
price: 5.99,
},
{
id: 1,
name: 'hamburger',
category: 'american',
price: 7.99,
},
{
id: 2,
name: 'other hamburger',
category: 'american',
price: 7.99,
},
];
console.log(
[
...items.reduce(
(result, item) => (
result.get(item.category)
? result.get(item.category).push(item.id)
: result.set(item.category, [item.id]),
result
),
new Map(),
),
].map(([label, value]) => ({ label, value })),
);
在组件中,它将如下所示:
options={[
...this.props.meals.reduce(
(result, item) => (
result.get(item.category)
? result.get(item.category).push(item.id)
: result.set(item.category, [item.id]),
result
),
new Map(),
),
].map(([label, value]) => ({ label, value }))}
答案 1 :(得分:1)
映射到您的this.props.meals
数组,并创建所需的选项数组,
<Select
isMulti
isSearchable
placeholder={"catégories"}
value={selectedOption}
onChange={this.handleChange}
options={this.props.meal.map(item=>({value: item.id, label: item.name}))}
/>
答案 2 :(得分:1)
您只需要“ name”属性,因此在绘制餐点地图时,只需对其进行检索。然后大写第一个字母。
const meals = [{
id: 0,
name: "spaghettis",
category: "italian",
price: 5.99
},
{
id: 1,
name: "hamburger",
category: "american",
price: 7.99
}
]
const result = meals.map(({name}) => ({
label: `${name[0].toUpperCase()}${name.slice(1)}`,
value: name
}))
console.log(result);
答案 3 :(得分:1)
您可以使用getOptionLabel
和getOptionValue
道具。
<Select
options={this.props.meals},
getOptionLabel={m => m.name}
getOptionValue={m => m.id} />
https://react-select.com/props
getOptionLabel generic = (option) => string
将选项数据解析为字符串,以供组件显示为标签
getOptionValue generic = (option) => string
将选项数据解析为字符串以比较选项并指定值属性