如何使用 useStyle 在 Material UI 中设置类组件的样式



我想使用 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

像已经说过的其他答案一样,您应该使用withStyles来扩充组件并通过属性传递classes。我冒昧地将 Material-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 */
  );
}
如何使用

类组件在类名中添加多个类

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
    );
  }
}

相关内容

  • 没有找到相关文章