Reusable component using theme-based Box features

。_饼干妹妹 提交于 2021-01-29 04:10:45

问题


I'd like to create a reusable component using Material-UI's api (not using styled-components.) I got this far - and it almost works - but the settings that use theme variable don't work (e.g, bgcolor and padding). Am I doing something wrong - or is this not possible?

  const BigPanel = styled(Box)({
    display: 'flex',
    width: '100%',
    flexgrow: 1,
    bgcolor: 'background.paper',
    borderRadius: 10,
    boxShadow:'1',
    p:{ xs: 4, md: 8 }
  });

回答1:


The object passed to styled is intended to be CSS properties, but you have a mixture of CSS properties and Box props (bgcolor, p). Even the ones that are valid CSS properties (display, width) are also valid Box props, so the most straightforward solution is to specify all of them as props.

One way to handle this is to use defaultProps. This makes it very easy to override some of the props when using the component by specifying them explicitly as shown in the example below.

import React from "react";
import Box from "@material-ui/core/Box";
import CssBaseline from "@material-ui/core/CssBaseline";
import { styled } from "@material-ui/core/styles";

const BigPanel = styled(Box)({});
BigPanel.defaultProps = {
  display: "flex",
  width: "100%",
  borderRadius: 10,
  flexGrow: 1,
  bgcolor: "background.paper",
  p: { xs: 4, md: 8 },
  boxShadow: "1"
};
export default function App() {
  return (
    <>
      <CssBaseline />
      <BigPanel>Default BigPanel</BigPanel>
      <BigPanel bgcolor="primary.main" color="primary.contrastText">
        BigPanel with explicit props
      </BigPanel>
    </>
  );
}

In the example above, styled isn't really serving any purpose anymore except to create a new component type. Though it isn't less code, below is an alternative way to get the same effect without using styled:

const BigPanel = React.forwardRef(function BigPanel(props, ref) {
  return <Box ref={ref} {...props} />;
});
BigPanel.defaultProps = {
  display: "flex",
  width: "100%",
  borderRadius: 10,
  flexGrow: 1,
  bgcolor: "background.paper",
  p: { xs: 4, md: 8 },
  boxShadow: "1"
};



来源:https://stackoverflow.com/questions/63382653/reusable-component-using-theme-based-box-features

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!