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

如何使用Styled Components为Material-UI Drawer组件设置样式

Fixing Styled Components Styling for MUI Drawer's Paper Element

Got it, let's break down why your current approach isn't working and how to fix it!

The issue here is that when you use styled(Drawer) directly, you're applying styles to the root element of the Drawer component, not the internal paper element that you want to customize. MUI's Drawer wraps its content in a child div with the class MuiDrawer-paper, so your styles aren't targeting that specific element.

Solution 1: Target the Internal Paper Class with a Nested Selector

Use styled-components' nested styling to directly target the MuiDrawer-paper class inside your StyledDrawer:

import styled from 'styled-components';
import Drawer from '@mui/material/Drawer';

export const StyledDrawer = styled(Drawer)`
  & .MuiDrawer-paper {
    position: relative;
    width: 240px;
  }
`;

This works because the & refers to the root Drawer element, and we're selecting its child with the MuiDrawer-paper class to apply your custom styles.

Solution 2: Pass a Styled Class to the Drawer's classes Prop

If you prefer more explicit control, you can create a styled div for the paper and pass its class name to the Drawer's classes.paper prop:

import styled from 'styled-components';
import Drawer from '@mui/material/Drawer';

// Create a styled component for the paper element
const StyledDrawerPaper = styled.div`
  position: relative;
  width: 240px;
`;

// Use it in your component
<Drawer variant="permanent" classes={{ paper: StyledDrawerPaper.className }}>
  {/* Your drawer content here */}
</Drawer>

Both approaches will apply your desired styles to the Drawer's paper element correctly. The first method is more concise if you only need to style the paper, while the second gives you more flexibility if you want to reuse the paper style elsewhere.

内容的提问来源于stack exchange,提问作者James

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 07:47:01