如何仅为Material-UI TreeView中选中的TreeItem设置样式?
The issue you're facing happens because the color property is inherited by default in CSS—when you apply color: red directly to the selected class (added to the root of the selected TreeItem), all child TreeItems inherit that red text color automatically.
To target only the selected TreeItem itself (and not its entire subtree), you need a more specific selector that styles the content area of the selected node directly, instead of applying styles that cascade down to children. Here's how to fix it:
Solution: Use a direct child selector to target the selected node's content
Modify your custom TreeItem styling to target the MuiTreeItem-content element that's an immediate child of the selected TreeItem:
const TreeItem = withStyles({ selected: { // Only apply styles to the content of the directly selected TreeItem "& > .MuiTreeItem-content": { color: "red" }, // Optional: Remove the default selected background color if you don't need it "& > .MuiTreeItem-content.Mui-selected": { backgroundColor: "transparent" } } })(MuiTreeItem);
Why this works:
- The
& > .MuiTreeItem-contentselector ensures we only affect the content element that's a direct child of the selected TreeItem's root. - Child TreeItems have their own
MuiTreeItem-contentelements, but these aren't direct children of the parent's root—so they won't inherit the red color.
Full modified code
Here's the complete updated component with the fix applied:
import React from "react"; import { makeStyles } from "@material-ui/core/styles"; import TreeView from "@material-ui/lab/TreeView"; import ExpandMoreIcon from "@material-ui/icons/ExpandMore"; import ChevronRightIcon from "@material-ui/icons/ChevronRight"; import MuiTreeItem from "@material-ui/lab/TreeItem"; import { withStyles } from "@material-ui/core/styles"; const useStyles = makeStyles({ root: { height: 240, flexGrow: 1, maxWidth: 400 } }); const TreeItem = withStyles({ selected: { "& > .MuiTreeItem-content": { color: "red" } } })(MuiTreeItem); export default function FileSystemNavigator() { const classes = useStyles(); return ( <TreeView className={classes.root} defaultCollapseIcon={<ExpandMoreIcon />} defaultExpandIcon={<ChevronRightIcon />} > <TreeItem nodeId="1" label="Applications"> <TreeItem nodeId="2" label="Calendar" /> <TreeItem nodeId="3" label="Chrome" /> <TreeItem nodeId="4" label="Webstorm" /> </TreeItem> <TreeItem nodeId="5" label="Documents"> <TreeItem nodeId="10" label="OSS" /> <TreeItem nodeId="6" label="Material-UI"> <TreeItem nodeId="7" label="src"> <TreeItem nodeId="8" label="index.js" /> <TreeItem nodeId="9" label="tree-view.js" /> </TreeItem> </TreeItem> </TreeItem> </TreeView> ); }
Now when you select a parent node, only its label will turn red—child nodes will stay their default color. Selecting a child node will only affect that specific node.
内容的提问来源于stack exchange,提问作者dmarr

