How to use useStyle to style Class Component in Material Ui

前端 未结 5 1889
我寻月下人不归
我寻月下人不归 2020-12-14 14:39

I want to use useStyle to style the Class Component . But this can be easily done hooks. but i want to use Component instead. But I cant figure out how to do this.

5条回答
  •  情歌与酒
    2020-12-14 14:49

    Like other answers already stated you should use withStyles to augment a component and pass the classes through the properties. I've taken the liberty to modify the Material-UI stress test example into a variant that uses a class component.

    Note that the withTheme: true option is normally not needed when you simply want to use the styles. It is needed in this example because the actual value of the theme is used in the render. Setting this option makes theme available through the class properties. The classes prop should always be provided, even if this option is not set.

    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 (
          
    rendered {++this.rendered} times
    color: {theme.color}
    backgroundColor: {backgroundColor}
    ); } }); 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 (
    ); } ReactDOM.render(, document.querySelector("#root"));
    
    
    
    
    
    

提交回复
热议问题