gpt4 book ai didi

javascript - 如何在 ReactJS 中制作具有特定值的下拉列表?

转载 作者:行者123 更新时间:2023-11-30 20:23:46 25 4
gpt4 key购买 nike

我正在使用 PrimeReactDropdown

我有这段代码,但在 Dropdown 中我只能显示 label 而不是 name

如何在Dropdown菜单中显示optionsSearch变量的每个元素的名称来选择这些名称?

import React, {Component} from 'react';
import {Dropdown} from 'primereact/components/dropdown/Dropdown';

class OptionsExample extends Component {
constructor(props) {
super(props);
this.state = {
optionsSearch: 'FORM_FIELDS'
};
}

onOptionChange = e => {
this.setState({optionsSearch: e.value});
}

render() {
const optionsSearch = [
{key: 'NAME1', name: 'NAME1', label: 'DESCRIPTION1'},
{key: 'NAME2', name: 'NAME2', label: 'DESCRIPTION2'},
{key: 'NAME3', name: 'NAME3', label: 'DESCRIPTION3'}
];

return (
<div>
<div className='ui-g-12 ui-md-12 ui-lg-12'>
<Dropdown value={this.state.optionsSearch} options={optionsSearch} onChange={this.onOptionChange} style={{width: '180px'}} placeholder={`${this.state.optionsSearch}`} />
</div>
</div>
);
}
}

export default OptionsExample;

最佳答案

此代码是从下拉列表的 PrimeReact 源代码中复制的。

https://github.com/primefaces/primereact/blob/master/src/components/dropdown/DropdownItem.js

render() {
let className = classNames('ui-dropdown-item ui-corner-all', {
'ui-state-highlight': this.props.selected,
'ui-dropdown-item-empty': (!this.props.label || this.props.label.length === 0)
});
let content = this.props.template ? this.props.template(this.props.option) : this.props.label;

return (
<li className={className} onClick={this.onClick}>
{content}
</li>
);
}

如您所见,{content} 正在为每个下拉项呈现,其中仅包含“标签”。

let content = this.props.template ? this.props.template(this.props.option) : this.props.label;

因此如果你想显示“名称”,你必须把它放在标签中。

他们的演示也只使用“label”和“value”属性。

https://www.primefaces.org/primereact/#/dropdown

编辑感谢@Chris G

您也可以呈现自定义内容,但是您必须将模板函数传递给下拉列表。

他们的演示展示了这一点。

carTemplate(option) {
if(!option.value) {
return option.label;
}
else {
var logoPath = 'showcase/resources/demo/images/car/' + option.label + '.png';

return (
<div className="ui-helper-clearfix">
<img alt={option.label} src={logoPath} style={{display:'inline-block',margin:'5px 0 0 5px'}} width="24"/>
<span style={{float:'right',margin:'.5em .25em 0 0'}}>{option.label}</span>
</div>
);
}
}

然后他们将其传递给 Dropdown 组件。

<Dropdown value={this.state.car} options={cars} onChange={this.onCarChange} itemTemplate={this.carTemplate} style={{width:'150px'}} placeholder="Select a Car"/>

关于javascript - 如何在 ReactJS 中制作具有特定值的下拉列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51150757/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com