默认方式Select
渲染所选值就是渲染其子项。在里面选择源代码 https://github.com/mui-org/material-ui/blob/v4.5.2/packages/material-ui/src/Select/SelectInput.js#L244当它循环遍历 Select 的子项时,它会执行以下操作:
selected = areEqualValues(value, child.props.value);
if (selected && computeDisplay) {
displaySingle = child.props.children;
}
这是基于以下假设Select
having MenuItem
孩子们。例如,在以下示例中,将选择第一个 MenuItem,并且该 MenuItem 的子项将是文本“Item 1”:
<Select value={1}>
<MenuItem value={1}>Item 1</MenuItem>
<MenuItem value={2}>Item 2</MenuItem>
</Select>
您的 Chips 没有子项,因此不会显示任何内容。您可以通过指定来自定义此行为renderValue
属性于Select
。这是一个接收值并可以决定渲染什么的函数。
以下示例显示了使用renderValue
渲染一个道具Chip
:
import React, { useState } from "react";
import ReactDOM from "react-dom";
import FormControl from "@material-ui/core/FormControl";
import Chip from "@material-ui/core/Chip";
import Select from "@material-ui/core/Select";
import { withStyles } from "@material-ui/core/styles";
const styles = theme => ({
formControl: {
margin: theme.spacing.unit,
minWidth: 120
}
});
const chipOptions = [
{ key: 1, text: "text1", value: "text1" },
{ key: 2, text: "text2", value: "text2" },
{ key: 3, text: "text3", value: "text3" }
];
function App({ classes }) {
const [value, setValue] = useState("text1");
const renderChip = value => {
return <Chip label={value} className={classes.chip} />;
};
return (
<>
<FormControl className={classes.formControl}>
<Select
inputProps={{
name: "badge",
id: "badge-simple"
}}
renderValue={renderChip}
value={value}
onChange={event => {
console.log(event.target.value);
setValue(event.target.value);
}}
>
{chipOptions &&
chipOptions.map(option => (
<Chip
key={option.value}
label={option.value}
className={classes.chip}
value={option.value}
/>
))}
</Select>
</FormControl>
</>
);
}
const StyledApp = withStyles(styles)(App);
const rootElement = document.getElementById("root");
ReactDOM.render(<StyledApp />, rootElement);