You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React结合Material UI时,Drawer组件无法渲染内部子组件的问题求助

React结合Material UI时,Drawer组件无法渲染内部子组件的问题求助

嘿,我仔细瞅了你的代码,马上就找到问题根源了——你的DrawerForm组件压根没把外部传入的子元素渲染出来!

你看,在CustomMap里调用DrawerForm的时候,明明把包含三个DateChart的Box作为子组件传进去了:

<DrawerForm
  drawerWidth={drawerWidth}
  variant={"persistent"}
  open={showViewController}
  close={handleCloseViewController}
>
  <Box
    sx={{
      position: "relative",
      top: "130px",
    }}
  >
    <DateChart divID="chart1" />
    <DateChart divID="chart2" />
    <DateChart divID="chart3" />
  </Box>
</DrawerForm>

但你的DrawerForm组件定义里,既没接收children这个props,也没在内部的Drawer里渲染它:

export const DrawerForm = ({
  drawerWidth,
  variant,
  anchor = "right",
  open,
  close,
  color = "white",
}) => {
  return (
    <Drawer
      sx={{
        width: drawerWidth,
        flexShrink: 0,
        "& .MuiPaper-root": {
          width: drawerWidth,
          backgroundColor: color,
        },
      }}
      variant={variant}
      anchor={anchor}
      open={open}
    >
      <FabForm
        top="75px"
        icon="arrowRight"
        handleClick={close}
      />
      {/* 这里完全没处理外部传入的子组件! */}
    </Drawer>
  );
};

解决方法超简单,只需要两步:

  • 给DrawerForm的props列表加上children参数
  • 在Drawer内部合适的位置(比如FabForm下方)渲染{children}

修改后的DrawerForm代码如下:

export const DrawerForm = ({
  drawerWidth,
  variant,
  anchor = "right",
  open,
  close,
  color = "white",
  children, // 新增接收children参数
}) => {
  return (
    <Drawer
      sx={{
        width: drawerWidth,
        flexShrink: 0,
        "& .MuiPaper-root": {
          width: drawerWidth,
          backgroundColor: color,
        },
      }}
      variant={variant}
      anchor={anchor}
      open={open}
    >
      <FabForm
        top="75px"
        icon="arrowRight"
        handleClick={close}
      />
      {children} {/* 在这里渲染外部传入的子组件 */}
    </Drawer>
  );
};

这样改完之后,你传入的Box和里面的三个DateChart就能正常显示在Drawer里啦!

备注:内容来源于stack exchange,提问作者Marco Bravo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.23 10:52:40