Material-UI select设置树结构
时间: 2024-01-08 19:02:38 浏览: 136
树结构菜单
要在Material-UI的Select组件中使用树结构,你可以使用Recursive Tree组件。以下是一个示例代码:
```jsx
import React from 'react';
import PropTypes from 'prop-types';
import { makeStyles } from '@material-ui/core/styles';
import TreeView from '@material-ui/lab/TreeView';
import TreeItem from '@material-ui/lab/TreeItem';
import ExpandMoreIcon from '@material-ui/icons/ExpandMore';
import ChevronRightIcon from '@material-ui/icons/ChevronRight';
import FormControl from '@material-ui/core/FormControl';
import InputLabel from '@material-ui/core/InputLabel';
import Select from '@material-ui/core/Select';
const data = {
id: 'root',
name: 'Parent Node',
children: [
{
id: '1',
name: 'Child Node 1',
children: [
{
id: '2',
name: 'Subchild Node 1',
},
{
id: '3',
name: 'Subchild Node 2',
},
],
},
{
id: '4',
name: 'Child Node 2',
children: [
{
id: '5',
name: 'Subchild Node 3',
},
{
id: '6',
name: 'Subchild Node 4',
},
],
},
],
};
const useStyles = makeStyles({
root: {
height: 240,
flexGrow: 1,
maxWidth: 400,
},
});
function renderTreeItems(items) {
return (
<>
{items.map((item) => (
<TreeItem key={item.id} nodeId={item.id} label={item.name}>
{Array.isArray(item.children) ? renderTreeItems(item.children) : null}
</TreeItem>
))}
</>
);
}
function RecursiveTreeView(props) {
const classes = useStyles();
const { onChange, value } = props;
const handleChange = (event) => {
onChange(event.target.value);
};
return (
<FormControl className={classes.formControl}>
<InputLabel htmlFor="tree-select">Select</InputLabel>
<Select
native
value={value}
onChange={handleChange}
inputProps={{
name: 'tree-select',
id: 'tree-select',
}}
>
<option value="" />
{renderTreeItems([data])}
</Select>
</FormControl>
);
}
RecursiveTreeView.propTypes = {
onChange: PropTypes.func.isRequired,
value: PropTypes.string.isRequired,
};
export default function SelectWithTree() {
const [value, setValue] = React.useState('');
const handleChange = (newValue) => {
setValue(newValue);
};
return (
<RecursiveTreeView onChange={handleChange} value={value} />
);
}
```
在这个示例中,我们首先定义了一个树形数据结构,然后使用`renderTreeItems()`函数递归渲染树形结构。最后,在`RecursiveTreeView`组件中,我们使用`FormControl`和`Select`组件来显示树形结构,并在选择时触发`onChange`事件。你可以根据自己的需要来修改这个示例。
阅读全文