programing

재료 UI에서 클래스 구성요소를 스타일링하기 위해 useStyle을 사용하는 방법

newnotes 2023. 3. 31. 22:41
반응형

재료 UI에서 클래스 구성요소를 스타일링하기 위해 useStyle을 사용하는 방법

useStyle을 사용하여 클래스 컴포넌트를 스타일링하고 싶습니다.하지만 쉽게 훅할 수 있지만 대신 컴포넌트를 사용하고 싶습니다.하지만 어떻게 해야 할지 모르겠어요.

import React,{Component} from 'react';
import Avatar from '@material-ui/core/Avatar';
import { makeStyles } from '@material-ui/core/styles';
import LockOutlinedIcon from '@material-ui/icons/LockOutlined';


    const useStyles = makeStyles(theme => ({
      '@global': {
        body: {
          backgroundColor: theme.palette.common.white,
        },
      },
      paper: {
        marginTop: theme.spacing(8),
        display: 'flex',
        flexDirection: 'column',
        alignItems: 'center',
      },
      avatar: {
        margin: theme.spacing(1),
        backgroundColor: theme.palette.secondary.main,
      }
}));

class SignIn extends Component{
  const classes = useStyle(); // how to assign UseStyle
  render(){
     return(
    <div className={classes.paper}>
    <Avatar className={classes.avatar}>
      <LockOutlinedIcon />
    </Avatar>
    </div>
  }
}
export default SignIn;

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

import { withStyles } from "@material-ui/core/styles";

const styles = theme => ({
  root: {
    backgroundColor: "red"
  }
});

class ClassComponent extends Component {
  state = {
    searchNodes: ""
  };

  render() {
    const { classes } = this.props;
    return (
      <div className={classes.root}>Hello!</div>
    );
  }
}

export default withStyles(styles, { withTheme: true })(ClassComponent);

그냥 무시하세요.withTheme: true테마를 사용하지 않는 경우.


이것을 TypeScript 로 동작시키려면 , 다음의 몇개의 변경이 필요합니다.

import { createStyles, withStyles, WithStyles } from "@material-ui/core/styles";

const styles = theme => createStyles({
  root: {
    backgroundColor: "red"
  }
});

interface Props extends WithStyles<typeof styles>{ }

class ClassComponent extends Component<Props> {

// the rest of the code stays the same

클래스 컴포넌트에 사용할 수 있습니다.withStyles대신makeStyles

import { withStyles } from '@material-ui/core/styles';

const useStyles = theme => ({
fab: {
  position: 'fixed',
  bottom: theme.spacing(2),
  right: theme.spacing(2),
},
  });

class ClassComponent extends Component {
   render() {
            const { classes } = this.props;

            {/** your UI components... */}
      }
} 


export default withStyles(useStyles)(ClassComponent)

이봐, 나도 비슷한 문제가 있었어.교환으로 해결했습니다.makeStyles와 함께withStyles그런 다음, 그 시점에서,const classes = useStyle();, 로 대체합니다.const classes = useStyle;

눈치채셨겠죠?useStyle는 함수 호출이 아니라 변수 할당이어야 합니다.

그 변경을 하면 잘 될 겁니다.

useStyles리액트 훅입니다기능 구성 요소에서만 사용할 수 있습니다.

이 행은 후크를 작성합니다.

const useStyles = makeStyles(theme => ({ /* ... */ });

함수 컴포넌트 내에서 클래스 오브젝트를 작성하기 위해 사용하고 있습니다.

const classes = useStyles();

그런 다음 jsx에서 클래스를 사용합니다.

<div className={classes.paper}>

권장 리소스: https://material-ui.com/styles/basics/ https://reactjs.org/docs/hooks-intro.html

이미 설명한 다른 답변과 마찬가지로 컴포넌트를 보강하고 다음 컴포넌트를 통과시키기 위해 사용해야 합니다.classes부동산에 접속합니다.재료 UI 스트레스 테스트의 예를 클래스 구성요소를 사용하는 변형으로 수정했습니다.

주의:withTheme: true일반적으로 스타일을 사용하려는 경우에는 옵션이 필요하지 않습니다.이 예에서는 테마의 실제 값이 렌더링에 사용되기 때문에 이 값이 필요합니다.이 옵션을 설정하면theme클래스 속성을 통해 사용할 수 있습니다.classes이 옵션이 설정되어 있지 않은 경우에도 항상 프로포트를 제공해야 합니다.

const useStyles = MaterialUI.withStyles((theme) => ({
  root: (props) => ({
    backgroundColor: props.backgroundColor,
    color: theme.color,
  }),
}), {withTheme: true});

const Component = useStyles(class extends React.Component {
  rendered = 0;

  render() {
    const {classes, theme, backgroundColor} = this.props;
    return (
      <div className={classes.root}>
        rendered {++this.rendered} times
        <br />
        color: {theme.color}
        <br />
        backgroundColor: {backgroundColor}
      </div>
    );
  }
});

function StressTest() {
  const [color, setColor] = React.useState('#8824bb');
  const [backgroundColor, setBackgroundColor] = React.useState('#eae2ad');

  const theme = React.useMemo(() => ({ color }), [color]);
  const valueTo = setter => event => setter(event.target.value);

  return (
    <MaterialUI.ThemeProvider theme={theme}>
      <div>
        <fieldset>
          <div>
            <label htmlFor="color">theme color: </label>
            <input
              id="color"
              type="color"
              onChange={valueTo(setColor)}
              value={color}
            />
          </div>
          <div>
            <label htmlFor="background-color">background-color property: </label>
            <input
              id="background-color"
              type="color"
              onChange={valueTo(setBackgroundColor)}
              value={backgroundColor}
            />
          </div>
        </fieldset>
        <Component backgroundColor={backgroundColor} />
      </div>
    </MaterialUI.ThemeProvider>
  );
}

ReactDOM.render(<StressTest />, document.querySelector("#root"));
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700&display=swap" />
<link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons" />
<script src="https://unpkg.com/react@16/umd/react.production.min.js"></script>
<script src="https://unpkg.com/react-dom@16/umd/react-dom.production.min.js"></script>
<script src="https://unpkg.com/@material-ui/core@4/umd/material-ui.production.min.js"></script>
<div id="root"></div>

다른 방법은 약간 회피책이긴 하지만요.

어떤 사람들은 이것이 그 질문에 정말 답하지 않는다고 말할지 모르지만, 나는 그렇다고 주장한다.최종 결과는useStyles()는 클래스 베이스이면서 멀티 파트 부모 컴포넌트의 스타일링을 제공합니다.

내 경우, 내가 전화할 수 있도록 표준 Javascript 클래스 내보내기가 필요했다.new MyClass()없이MyClass is not a constructor에러입니다.

import { Component } from "./react";
import { makeStyles } from "@material-ui/core/styles";

const useStyles = makeStyles((theme) => ({
  someClassName: {
    ...
  }
}));

export default class MyComponent extends Component {
  render() {
    return <RenderComponent {...this.props} />;
  }
}

function RenderComponent(props) {
  const classes = useStyles();

  return (
    /* JSX here */
  );
}

클래스 컴포넌트와 함께 ClassName에 여러 클래스를 추가하는 방법

import { withStyles } from "@material-ui/core/styles";

const styles = theme => ({
  root: {
    backgroundColor: "red"
  },
  label: {
    backGroundColor:"blue"
 }
});

class ClassComponent extends Component {
  state = {
    searchNodes: ""
  };

  render() {
    const { classes } = this.props;//   
    return (
      <div className={classes.root + classes.label}>Hello!</div> //i want to add label style also with
    );
  }
}

언급URL : https://stackoverflow.com/questions/56554586/how-to-use-usestyle-to-style-class-component-in-material-ui

반응형