简体   繁体   中英

@mui/system -- how to pass transient props to styled()

I'm using import { styled } from "@mui/system" ; like so:

const Column = styled("div")<ColumnProps>`
  background: ${(props) => props.backgroundColor ?? "blue"};
`;

export default function App() {
  return (
    <div>
      <Column backgroundColor={"green"}>column</Column>
    </div>
  );

and it is producing the following error:

Warning: React does not recognize the `backgroundColor` prop on a DOM element.

how can I pass a prop like this without having it trigger such an error? styled-components has "transient-props' that can be invoked with $ but that does not work with @mui/system

In Emotion, this is handled via shouldForwardProp .

Here's a modified version of your sandbox:

import { styled } from "@mui/system";

type ColumnProps = {
  backgroundColor?: string;
};

const Column = styled("div", {
  shouldForwardProp: (prop) => prop !== "backgroundColor"
})<ColumnProps>`
  background: ${(props) => props.backgroundColor ?? "blue"};
`;

export default function App() {
  return (
    <div>
      <Column backgroundColor={"green"}>column</Column>
    </div>
  );
}

编辑 React Typescript(分叉)

MUI documentation: https://mui.com/system/styled/#heading-styled-component-options-styles-component

I use utility function for it, so I always type prop names correctly:

export const shouldForwardProp = <CustomProps extends Record<string, unknown>>(
  props: Array<keyof CustomProps>,
  prop: PropertyKey,
): boolean => !props.includes(prop as string);

const MyComponent = styled('div', {
  shouldForwardProp: (prop) => shouldForwardProp<MyComponentProps>(['isDisabled', 'bgColor'], prop),
})<MyComponentProps>(({ theme, isDisabled, size, bgColor }) => ({
...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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