reactjs - 如何使用 react-select 在每个下拉项下方自定义呈现子文本?
问题描述
我试图弄清楚如何利用 react-select 中的自定义组件来呈现包含带有潜文本的项目的下拉列表。
我查看了以下每个组件:https ://react-select.com/components ,但不确定哪一个最适合我的需求。
通过查看组件列表,我相信该option
组件是用于类似的东西并且可能会起作用,但我不确定。有人可以验证我的想法吗?
解决方案
React-select V2+ 解决方案:
您是绝对正确的,使用Option
组件将允许您格式化每个选项,menuList
如下例所示:
const options = [
{
label: "text 1",
subLabel: "subtext 1",
value: "1"
},
{
label: "text 2",
subLabel: "subtext 2",
value: "2"
},
{
label: "text 3",
subLabel: "subtext 3",
value: "3"
},
{
label: "text 4",
subLabel: "subtext 4",
value: "4"
}
];
const Option = props => {
return (
<components.Option {...props}>
<div>{props.data.label}</div>
<div style={{ fontSize: 12 }}>{props.data.subLabel}</div>
</components.Option>
);
};
function App() {
return (
<div className="App">
<Select options={options} components={{ Option }} />
</div>
);
}
这里有一个活生生的例子。
React-select V1 解决方案:
保持与 V2 解决方案相同的结构,您可以通过使用如下道具传递渲染函数来实现显示自定义选项元素optionRenderer
:
class App extends Component {
renderOption = option => (
<div>
<label>{option.label}</label>
<label style={{ display: "block", color: "gray", fontSize: 12 }}>
{option.subLabel}
</label>
</div>
);
render() {
return (
<div className="App">
<Select options={options} optionRenderer={this.renderOption} />
</div>
);
}
}
这里有一个活生生的例子。
推荐阅读
- json - 在golang中解组json数组时出错
- java - 如何从另一个布局的片段中查找ViewById,而不是作为根布局膨胀的那个?
- python - 有没有办法通过 Amazon EC2 (Amazon Linux 2) 实例中的用户数据启用 python virtualenv?
- docker - 如何使用 Compose 创建具有用户定义的 IP 和 MAC 地址的 Docker macvlan
- c - 如何在同一进程中使用管道(线程安全)
- c++11 - C++ 使用指针访问成员函数
- c# - 如何使用动画 xamarin 表单增加和减少 flex 布局的高度
- javascript - ng-bootstrap datepicker 无法在选择之前设置默认日期
- python - Python XGBoost 生成预测数学方程
- python - 关闭局部值