简体   繁体   中英

Access props inside the styled component using MUI

I'm trying to create a custom button component using MUI on a React JS project. I've checked the docs and I discovered that I can do this using styled components. All worked well with the code presented below. The problem is that I want to create a more "customizable" component. I have inside my theme file 2 sets of colors (primary and secondary). The fact is that I want to create a button that is able to take a prop for this set of colors (primary / secondary).

import * as React from 'react';
import ButtonUnstyled, {
  buttonUnstyledClasses,
  ButtonUnstyledProps,
} from '@mui/core/ButtonUnstyled';
import { styled } from '@mui/system';
import { theme } from '../../theme';

const CustomButtonRoot = styled('button')(`
  background-color: ${theme.palette[props.type].main};
  padding: 15px 20px;
  border-radius: 10px;
  color: #fff; 
`);

interface TodoButtonProps {
    unstyledProps: ButtonUnstyledProps,
    type?: 'primary' | 'secondary'
}

function CustomButton(props: TodoButtonProps) {
  return <ButtonUnstyled {...props} component={CustomButtonRoot} />;
}

export default CustomButton

The question is: How I can include this prop inside the styled component code?

Pass a callback. In this callback the first argument is the props of the styled component. You can also use the style object instead of template string. More detail in this answer.

const CustomButtonRoot = styled("button")(
  ({ theme, myColor }) => `
  padding: 15px 20px;
  border-radius: 10px;
  color: ${myColor}; 
`
);
<CustomButton myColor="red">abc</CustomButton>

代码沙盒演示

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