【问题标题】:Enhancing from Component in React with Material-UI使用 Material-UI 从 React 中的组件进行增强
【发布时间】:2020-11-18 23:00:13
【问题描述】:

我正在使用 React 和 Material-UI。有没有办法从 React.Component 导出一个类?我想使用一些 React 变量,比如 state。如果这不可能,我该如何使用状态?

实际代码(作品):

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

const styles = makeStyles(() => ({
    style1: {
        fontSize: '12px'
    }
}));

const MyComponent = () => {
    const classes = styles();
    return(
        <Typography className={classes.style1}>Hello World</Typography>
    );
}

export default MyComponent;

我在寻找什么:

import React, { Component } from 'react';
import { Typography } from '@material-ui/core';
import { makeStyles } from '@material-ui/styles';

export default class MyComponent extends Component {
    constructor(props){
        super(props);
        this.classes = makeStyles(() => ({
            style1: {
                fontSize: '12px'
            }
        }));
    }

    render() {
        return(
            <Typography className={this.classes.style1}>Hello World</Typography>
        );
    }
}

【问题讨论】:

  • 您是否尝试过您的“我在寻找什么:”代码?
  • 引用类时出现了一些错误。它编译并在浏览器中显示,但组件没有获得样式
  • 也许您需要将该信息放入问题中。你尝试了什么? (你已经提到过)。跑步时会发生什么?您在运行时遇到了哪些错误或警告?

标签: javascript reactjs material-ui


【解决方案1】:

您正在使用makeStyles(),当您的组件是功能组件时使用。 makeStyles() 是一个 Hook API。

如果您使用的是 Class 组件,那么您必须使用 HOC 变体,即withStyles

示例取自 here:

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

const styles = {
  root: {
    backgroundColor: 'red',
  },
};

function MyComponent(props) {
  return <div className={props.classes.root} />;
}

export default withStyles(styles)(MyComponent);

withStyles() 可用于函数式组件和类组件,而makeStyles() 只能用于函数式组件。

您还可以对 HOC 变体使用装饰器语法,例如 here。但是你需要使用这个babel plugin,就像官方material-ui文档中提到的那样:

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

const styles = {
  root: {
    backgroundColor: 'red',
  },
};

@withStyles(styles)
class MyComponent extends React.Component {
  render () {
    return <div className={this.props.classes.root} />;
  }
}

export default MyComponent

【讨论】:

  • 谢谢@SkrewEverything。这行得通。我对装饰器有错误。为了修复它们,我使用了这个answere
猜你喜欢
  • 1970-01-01
  • 2019-10-17
  • 2016-03-22
  • 1970-01-01
  • 1970-01-01
  • 2020-11-23
  • 2020-11-18
  • 2020-06-24
  • 2016-10-17
相关资源
最近更新 更多