我正在根据文档示例使用Material UI Multiple Select。我需要保存所选选项的ID并显示名称,因此我渲染对象。当我使用带占位符的文档中的示例时,我看到的是ID而不是所选名称。 参见:https://codesandbox.io/s/kxz5yqmrzv?from-embed
const names = [
{ id: "a", name: "Oliver Hansen" },
{ id: "b", name: "Van Henry" },
{ id: "c", name: "April Tucker" },
{ id: "d", name: "Ralph Hubbard" },
{ id: "e", name: "Omar Alexander" },
{ id: "f", name: "Carlos Abbott" },
{ id: "g", name: "Miriam Wagner" },
{ id: "h", name: "Bradley Wilkerson" },
{ id: "i", name: "Virginia Andrews" },
{ id: "j", name: "Kelly Snyder" }
];
<Select
multiple
displayEmpty
value={this.state.name}
onChange={this.handleChange}
input={<Input id="select-multiple-placeholder" />}
renderValue={selected => {
if (selected.length === 0) {
return <em>Placeholder</em>;
}
return selected.join(", ");
}}
MenuProps={MenuProps}
>
<MenuItem disabled value="">
<em>Placeholder</em>
</MenuItem>
{names.map(name => (
<MenuItem
key={name.id}
value={name.id}
// style={getStyles(name, this)}
>
{name.name}
</MenuItem>
))}
</Select>
答案 0 :(得分:1)
Select只是在执行您在renderValue
函数中所要求的操作:
renderValue={selected => {
if (selected.length === 0) {
return <em>Placeholder</em>;
}
// This will return a comma-separated list of the values.
return selected.join(", ");
}}
您可以通过在选择值时使renderValue
未定义来让Material-UI找出正确的显示:
renderValue={
this.state.name.length > 0
? undefined
: () => <em>Placeholder</em>
}
还可以使用renderValue
数据结构来做更复杂的names
来将值转换为名称,但这仅在您要执行不同于默认值的操作时才需要呈现选定的值(例如在Chip演示中)。