繁体   English   中英

如何在树中选择父元素而不丢失孩子的“选定”样式

[英]How to select a parent element in tree and not lose child's 'selected' styles

我有一个 MUI TreeView 组件,其中包含类别(父)和文章(子)的嵌套映射。 当我选择一个孩子时,该孩子会根据“选定”应用样式。 当我单击父级时,前一个子级会丢失其“选定”样式。

如何区分“选中的子”和“选中的父(选中)”。

如果可能的话,我更愿意在 CSS 中完成这一切。 这是一个 Next.js 应用程序。

我的 CategoryItem CSS:

const StyledCategoryItemRoot = styled(TreeItem)(({ theme }) => ({
  [`& .${treeItemClasses.content}`]: {
    fontWeight: theme.typography.fontWeightBold,
    marginBottom: 5,
    paddingLeft: 0,
    borderRadius: theme.shape.borderRadius,
    '&.Mui-selected.Mui-focused, &:hover, &.Mui-selected:hover': {
      backgroundColor:
        theme.palette.mode === 'light'
          ? alpha('#ff9aff', 0.16)
          : alpha('#2f506f', 0.24),
    },
    '&.Mui-selected, &.Mui-focused': {
      backgroundColor: 'transparent',
    },
  },
}));

我的文章项 CSS:

const StyledArticleItemRoot = styled(TreeItem)(({ theme, router, post }) => ({
  color:
    theme.palette.mode === 'light'
      ? theme.palette.grey[900]
      : theme.palette.grey[500],
  [`& .${treeItemClasses.content}`]: {
    fontWeight: theme.typography.fontWeightBold,
    paddingLeft: 0,
    borderRadius: theme.shape.borderRadius,
    transition: '.2s',
    '&.Mui-selected:hover, &.Mui-selected.Mui-focused:hover, &:hover': {
      color: theme.palette.mode === 'light' ? theme.palette.grey[800] : 'white',
    },
    '&.Mui-focused, &.Mui-selected, &.Mui-selected.Mui-focused': {
      backgroundColor:
        theme.palette.mode === 'light'
          ? alpha('#ff9aff', 0.16)
          : alpha('#2f506f', 0.16),
      color:
        post.attributes.slug !== router.query.slug
          ? theme.palette.grey[500]
          : theme.palette.mode === 'light'
          ? theme.palette.primary.main
          : theme.palette.secondary.main,
    },
  },
}));

在 MUI 树视图组件中,如果 multiselect 关闭multiSelect={false}则只能选择一个节点(父节点或子节点),不能同时选择父节点和子节点!

所以如果你选择了子节点然后选择了父节点,子节点将失去选择的节点样式,因为它不再被选中

在评论中回答你的问题

我希望能够单击类别下拉列表而不会丢失文章上的“选定”样式。

您可以通过以下方式做到这一点:手动处理节点选择

<TreeView
   aria-label="file system navigator"
   key="treeView"
   defaultCollapseIcon={<ExpandMoreIcon />}
   defaultExpandIcon={<ChevronRightIcon />}
   multiSelect={false}
   selected={selectedNodes}
   onNodeSelect={(e, node_ids) => {
     handleClick(e, node_ids);
   }}> //add here tree nodes 
</TreeView>

现在在 handleClick 函数中,您将设置选定的节点:

setSelectedNodes(nodes_ids);

并且在单击的元素是节点标签而不是下拉菜单或可折叠图标时才选择它

所以 handleClick 看起来像这样:

 function handleClick(e, nodes_ids) {
  if (e.target.className == "MuiTreeItem-label") 
   setSelectedNodes(nodes_ids);
}

ps :不要忘记将 selectedNodes 添加到您的状态:

[selectedNodes, setSelectedNodes]=useState([]);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM