简体   繁体   中英

React add custom property to component

I am trying to create a variation of an MUI component. This all works fine, until I run the build command, and then it fails. I have a few variations of this, but basically I just want a custom property or attribute that changes some element of the component.

// RoundBox.js
import { styled } from "@mui/material/styles";
import MuiBox from "@mui/material/Box";

export const RoundBox = styled(MuiBox)(({roundish }) => ({
  borderRadius: roundish ? 5 : 15
}));

Using that component in another file like this:

<RoundBox>
 ... rounded content ...
</RoundBox>

<RoundBox roundish>
 ... very rounded content ...
</RoundBox>

This renders correctly, when I am running it in developer mode, however, when I try to build it, I am getting errors like this:

Type error: Type 'true' is not assignable to type 'ResponsiveStyleValue<MinWidth<string | number> | MinWidth<string | number>[] | undefined> | ((theme: Theme) => ResponsiveStyleValue<MinWidth<...> | MinWidth<...>[] | undefined>)'.

I'm writing this from memory, but you need to tell the compiler the type of the props you expect:

type RoundBoxProps = {
  roundish: boolean
}

export const RoundBox = styled<RoundBoxProps>(MuiBox)(({ roundish }) => ({
  borderRadius: roundish ? 5 : 15
}));

You could also simplify this by an inline type, if you expect just a few props:

export const RoundBox = styled<{ roundish: boolean }>(MuiBox)(({ roundish }) => ({
  borderRadius: roundish ? 5 : 15
}));

You can do it like

const RoundBox = styled(MuiBox)(({roundish}: {roundish: boolean}) => ({
  borderRadius: roundish ? 5 : 15
}));

or

<MuiBox sx={{ borderRadius: 5 }} />
<MuiBox sx={{ borderRadius: 15 }} />

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