source

MUI 스타일로 소품 전달

bestscript 2023. 2. 18. 20:43

MUI 스타일로 소품 전달

「 」가 되어 있는 Card여기와 같은 코드입니다.다음과 같이 카드 스타일 또는 재료 UI 스타일을 업데이트하려면 어떻게 해야 합니까?

const styles = theme => ({
  card: {
  minWidth: 275,
},

이에 대한 내용:

const styles = theme => ({
  card: {
  minWidth: 275, backgroundColor: props.color
},

최근에 나온 걸 먹어봤더니

Line 15:  'props' is not defined  no-undef

코드를 다음과 같이 업데이트 했을 때:

const styles = theme =>  (props) => ({
  card: {
  minWidth: 275, backgroundColor: props.color
},

또한.

 const styles  = (theme ,props) => ({
   card: {
   minWidth: 275, backgroundColor: props.color
 },

대신

const styles = theme => ({
  card: {
  minWidth: 275, backgroundColor: props.color
},

웹페이지에서 컴포넌트 카드 스타일이 지저분하게 나왔어요.

덧붙여서, 저는 다음과 같이 소품을 전달합니다.

<SimpleCard backgroundColor="#f5f2ff" />

도와주세요!

기존 답변은 삭제했습니다. 존재 이유가 없기 때문입니다.

원하는 것은 다음과 같습니다.

import React from 'react';
import { makeStyles } from '@material-ui/core';

const useStyles = makeStyles({
    firstStyle: {
        backgroundColor: props => props.backgroundColor,
    },
    secondStyle: {
        color: props => props.color,
    },
});

const MyComponent = ({children, ...props}) =>{
    const { firstStyle, secondStyle } = useStyles(props);
    return(
        <div className={`${firstStyle} ${secondStyle}`}>
            {children}
        </div>
    )
}

export default MyComponent;

다음과 같이 사용할 수 있습니다.

<MyComponent color="yellow" backgroundColor="purple">
    Well done
</MyComponent>

공식 문서

재료 UI에서 소품과 테마를 모두 사용하는 방법:

const useStyles = props => makeStyles( theme => ({
    div: {
        width: theme.spacing(props.units || 0)  
    }
}));

export default function ComponentExample({ children, ...props }){
    const { div } = useStyles(props)();
    return (
        <div className={div}>{children}</div>
    );
}

Typescript 솔루션은 다음과 같은 솔루션입니다.

import React from 'react';
import { makeStyles } from '@material-ui/core/styles';
import Button from '@material-ui/core/Button';
import {Theme} from '@material-ui/core';

export interface StyleProps {
    height: number;
}

const useStyles = makeStyles<Theme, StyleProps>(theme => ({
  root: {
    background: 'green',
    height: ({height}) => height,
  },
}));

export default function Hook() {

  const props = {
    height: 48
  }

  const classes = useStyles(props);
  return <Button className={classes.root}>Styled with Hook API</Button>;
}

가지고 놀고 싶다면 이 CodeSandbox에서 사용해 보세요.

MUI v5에서는 다음과 같이 스타일 객체를 작성할 때 소품에 액세스합니다.

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

const StyledBox = styled(Box)(({ theme, myColor }) => ({
  backgroundColor: myColor,
  width: 30,
  height: 30
}));

의 경우 을 '프롭 타입'에.CreateStyledComponent:

type DivProps = {
  myColor: string;
};

const Div = styled(Box)<DivProps>(({ theme, myColor }) => ({
  backgroundColor: myColor,
  width: 30,
  height: 30
}));
<StyledBox myColor="pink" />

커스텀 컴포넌트에 다음과 같은 시스템 소품을 사용하는 경우Box ★★★★★★★★★★★★★★★★★」Typography , 을 사용하면 .extendSxProp다음 예시와 같습니다.

import { unstable_extendSxProp as extendSxProp } from "@mui/system";

const StyledDiv = styled("div")({});

function DivWithSystemProps(inProps) {
  const { sx } = extendSxProp(inProps);
  return <StyledDiv sx={sx} />;
}
<DivWithSystemProps
  bgcolor="green"
  width={30}
  height={30}
  border="solid 1px red"
/>

설명.

  • styled("div")(): 추가sx 컴포넌트에
  • extendSxProp(props): 톱 레벨의 시스템 소품을 모아서sx★★★★
const props = { notSystemProps: true, color: 'green', bgcolor: 'red' };
const finalProps = extendSxProp(props);

// finalProps = {
//   notSystemProps: true,
//   sx: { color: 'green', bgcolor: 'red' }
// }

typescript와 함께 사용하려면 모든 시스템 속성의 유형을 추가해야 합니다.

type DivSystemProps = SystemProps<Theme> & {
  sx?: SxProps<Theme>;
};

function DivWithSystemProps(inProps: DivSystemProps) {
  const { sx, ...other } = extendSxProp(inProps);
  return <StyledDiv sx={sx} {...other} />;
}

Codesandbox 데모

여기 Material-UI 공식 데모가 있습니다.

여기 아주 간단한 예가 있습니다.Styled Components와 유사한 구문은 다음과 같습니다.

import React from "react";
import { makeStyles, Button } from "@material-ui/core";

const useStyles = makeStyles({
  root: {
    background: props => props.color,
    "&:hover": {
      background: props => props.hover
    }
  },
  label: { fontFamily: props => props.font }
});

export function MyButton(props) {
  const classes = useStyles(props);
  return <Button className={classes.root} classes={{ label: classes.label }}>My Button</Button>;
}


// and the JSX...
<MyButton color="red" hover="blue" font="Comic Sans MS" />

에서는 「」를 사용하고 있습니다.makeStyles단, 이 기능은및에서도 사용할 수 있습니다.

2018년 11월 3일 @material-ui/style로 처음 소개되었으며 버전 4부터는 @material-ui/core에 포함되었습니다.

이 답변은 버전 4.0보다 훨씬 이전 버전으로 작성되었습니다.

기능 컴포넌트를 꼭 하세요.makeStyles.

James Tan의 답변은 버전 4.x에 대한 최선의 답변입니다.

이 아래 있는 것은 모두 고대 것입니다.

★★★★★를 withStyles할 수 theme 않다.props.

이 기능을 요구하는 Github에 미해결의 문제가 있습니다.또, 코멘트 중 일부는, 고객이 흥미를 가지는 대체 솔루션에 대해 지적하는 경우가 있습니다.

소품을 사용하여 카드의 배경색을 변경하는 방법 중 하나는 인라인 스타일을 사용하여 이 속성을 설정하는 것입니다.원본 코드와 상자에 몇 가지 변경 사항을 포함했습니다. 수정된 버전을 보고 작동 상태를 확인할 수 있습니다.

제가 한 일은 다음과 같습니다.

  1. 를 렌더링합니다.backgroundColor 추가:
// in index.js
if (rootElement) {
  render(<Demo backgroundColor="#f00" />, rootElement);
}
  1. 카드에 인라인 스타일을 적용하려면 다음 받침대를 사용합니다.
    function SimpleCard(props) {
      // in demo.js
      const { classes, backgroundColor } = props;
      const bull = <span className={classes.bullet}>•</span>;
      return (
        <div>
          <Card className={classes.card} style={{ backgroundColor }}>
            <CardContent>
              // etc

렌더링된 카드컴포넌트의 배경은 빨간색(#F00)입니다.

기타 옵션에 대해서는 설명서의 "Overrides" 섹션을 참조하십시오.

@mui v5

styled() 유틸리티를 사용할 수 있습니다(올바른 것을 Import 합니다).shouldForwardProp the . 다음 예시는 음음음음음음음음음음음SomeProps a a div 표시

import { styled } from '@mui/material'

interface SomeProps {
  backgroundColor: 'red'|'blue',
  width: number
}
const CustomDiv  = styled('div', { shouldForwardProp: (prop) => prop !== 'someProps' })<{
  someProps: SomeProps;
}>(({ theme, someProps }) => {
  return ({
    backgroundColor: someProps.backgroundColor,
    width: `${someProps.width}em`,
    margin:theme.spacing(1)
  })
})
import React from "react";
import { makeStyles } from "@material-ui/styles";
import Button from "@material-ui/core/Button";

const useStyles = makeStyles({
  root: {
    background: props => props.color,
    "&:hover": {
      background: props => props.hover
    }
  }
});

export function MyButton(props) {
  const classes = useStyles({color: 'red', hover: 'green'});
  return <Button className={classes.root}>My Button</Button>;
}

에 a가 있었다.props 에서 사용하다withStyles되지 않았다고 하게 하다)

하지만 은 나에게를 들어, 「 a a a a a a」의).MenuItem

const StyledMenuItem = withStyles((theme) => ({
 root: {
  '&:focus': {
    backgroundColor: props => props.focusBackground,
    '& .MuiListItemIcon-root, & .MuiListItemText-primary': {
      color: props => props.focusColor,
    },
  },
 },
}))(MenuItem);

그런 다음 다음과 같이 사용합니다.

 <StyledMenuItem focusColor={'red'} focusBackground={'green'}... >...</StyledMenuItem>

Styles를 사용하여 Typescript의 전달 속성을 작업하는 데 몇 시간을 소비했습니다.온라인에서 찾은 솔루션 중 어떤 것도 제가 하려고 했던 것과 맞지 않았기 때문에 결국 저는 저만의 솔루션을 여기저기서 조금씩 짜맞추고 말았습니다.

예를 들어 재료 UI의 외부 구성요소가 기본 스타일을 제공하지만 구성요소에 다른 스타일링 옵션을 전달하여 재사용하려는 경우 이 방법이 작동합니다.

import * as React from 'react';
import { Theme, createStyles, makeStyles } from '@material-ui/core/styles';
import { TableCell, TableCellProps } from '@material-ui/core';

type Props = {
    backgroundColor?: string
}

const useStyles = makeStyles<Theme, Props>(theme =>
    createStyles({
        head: {
            backgroundColor: ({ backgroundColor }) => backgroundColor || theme.palette.common.black,
            color: theme.palette.common.white,
            fontSize: 13
        },
        body: {
            fontSize: 12,
        },
    })
);

export function StyledTableCell(props: Props & Omit<TableCellProps, keyof Props>) {
    const classes = useStyles(props);
    return <TableCell classes={classes} {...props} />;
}

완벽한 해결책은 아닐지 몰라도 효과가 있는 것 같아요.그들이 단지 Styles로 자산을 받아들이도록 수정하지 않은 것은 정말 골칫거리다.그러면 일이 훨씬 쉬워질 거야.

클래스 컴포넌트를 포함한 TypeScript 솔루션:

type PropsBeforeStyle = {
  propA: string;
  propB: number;
}

const styles = (theme: Theme) => createStyles({
  root: {
    color: (props: PropsBeforeStyle) => {}
  }
});

type Props = PropsBeforeStyle & WithStyles<typeof styles>;

class MyClassComponent extends Component<Props> {...}

export default withStyles(styles)(MyClassComponent);

export const renderButton = (tag, method, color) => {
  const OkButton = withStyles({
    root: {
      "color": `${color}`,
      "filter": "opacity(0.5)",
      "textShadow": "0 0 3px #24fda39a",
      "backgroundColor": "none",
      "borderRadius": "2px solid #24fda3c9",
      "outline": "none",
      "border": "2px solid #24fda3c9",
      "&:hover": {
        color: "#24fda3c9",
        border: "2px solid #24fda3c9",
        filter: "opacity(1)",
      },
      "&:active": {
        outline: "none",
      },
      "&:focus": {
        outline: "none",
      },
    },
  })(Button);
  return (
    <OkButton tag={tag} color={color} fullWidth onClick={method}>
      {tag}
    </OkButton>
  );
};

renderButton('Submit', toggleAlert, 'red')

MUI v5에서 API를 연결하기 위해 소품을 동적으로 전달하는 또 다른 방법이 있습니다.

import React from "react";
import { makeStyles } from "@mui/styles";
import { Theme } from "@mui/material";

interface StyleProps {
  height: number;
  backgroundColor: string;
}

const useStyles = makeStyles<Theme>((theme) => ({
  root: ({ height, backgroundColor }: StyleProps) => ({
    background: backgroundColor,
    height: height
  })
}));

export default function Hook() {
  const props = {
    height: 58,
    backgroundColor: "red"
  };

  const classes = useStyles(props);
  return (
    <button className={classes.root}>
      another way of passing props to useStyle hooks
    </button>
  );
}

코드 앤 박스 https://codesandbox.io/s/styles-with-props-forked-gx3bf?file = / codes . tsx : 0 - 607

다음은 MUI v5 스타일에 소품을 전달하는 방법에 대한 2가지 완전한 작업 예를 제시하겠습니다.css 또는 javascript 객체 구문을 사용합니다.

css 구문의 경우:

import { styled } from '@mui/system'

interface Props {
  myColor: string
}

const MyComponent = ({ myColor }: Props) => {
  const MyStyledComponent = styled('div')`
    background-color: ${myColor};

    .my-paragraph {
      color: white;
    }
  `
  return (
    <MyStyledComponent >
      <p className="my-paragraph">Hello there</p>
    </MyStyledComponent >
  )
}

export default MyComponent

, 이렇게 정의되어 있습니다.MyStyledComponent의 범위 내에서MyComponent할 수 styled()★★★★★★ 。

javascript 오브젝트 구문도 동일합니다.

import { styled } from '@mui/system'

const MyComponent = ({ className }: any) => {
  return (
    <div className={className}>
      <p className="my-paragraph">Hello there</p>
    </div>
  )
}

interface Props {
    myColor: string
  }

const MyStyledComponent = styled(MyComponent)((props: Props) => ({
  backgroundColor: props.myColor,
  '.my-paragraph': { color: 'white' },
}))

export default MyStyledComponent

두 예에서는 해 주세요.className스타일을 적용할 컴포넌트에 추가합니다.styled()는 a를 합니다.className★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★이치노, 「」는,div.

결과:

흰색 텍스트가 있는 빨간색 정사각형

이 방법에는 다른 다양한 종류가 있을 수 있지만, 이 두 가지 방법은 구현과 이해가 쉽습니다.

계산된 스타일을 메모해야 할 수도 있고, 소품이 많이 바뀌면 이 방법을 사용하지 않을 수도 있습니다.별로 성과가 없는 것 같아요.

사용.styled-components소품 통과 시에만 스타일을 적용하고 싶을 수 있습니다.이 경우 다음과 같은 작업을 수행할 수 있습니다(삭제).: {foo: boolean}TypeScript 를 사용하지 않는 경우:

const SAnchor = styled("a", {
  shouldForwardProp: prop => prop !== "foo",
})(({foo = false}: {foo: boolean}) => ({
  ...(foo && {
    color: "inherit",
    textDecoration: "none",
  }),
}));

개체 확산 소스

shouldForwardProp문서

@mui v5

JSON 오브젝트의 테마와 소품을 사용합니다.

const Answerdiv = styled((props) => {
const { item_style, ...other } = props;
return <div  {...other}></div>;
})(({ theme, item_style }) => {
    for(var i of Object.keys(item_style)){
        item_style[i] =Object.byString(theme,item_style[i])|| item_style[i];
}
    return (item_style)
});

컴포넌트 사용

<Answerdiv item_style={(item_style ? JSON.parse(item_style) : {})}>

Object.byString의 경우

Object.byString = function(o, s) {
        s = s.replace(/\[(\w+)\]/g, '.$1'); // convert indexes to properties
        s = s.replace(/^\./, '');           // strip a leading dot
        var a = s.split('.');
        for (var i = 0, n = a.length; i < n; ++i) {
            var k = a[i];
            if (k in o) {
                o = o[k];
            } else {
                return;
            }
        }
        return o;
    }

언급URL : https://stackoverflow.com/questions/48879517/passing-props-to-mui-styles