【问题标题】:Material-UI withStyles not adding classes to propsMaterial-UI withStyles 不向道具添加类
【发布时间】:2019-04-04 23:45:52
【问题描述】:

我正在尝试使用 Material-UI 的 withStyles 方法实现一些样式,但是我无法将类作为道具。关于我缺少什么的任何建议?我在下面包含了相关代码,但请注意,此文件中有一个 <App> 组件,为简洁起见,我将其省略。

import React from 'react'
import ReactDOM from "react-dom";
import {Paper, Typography} from '@material-ui/core'
import {withStyles} from '@material-ui/core/styles'
import NavBar from "./navBar";

class Recipe extends React.Component {
    constructor(props) {
        super(props);
    }

    componentDidMount() {
        console.log('Recipe Did Mount')
    }

    render() {
        const {recipeData, classes} = this.props;
        return (
            <Paper>
                <Typography className={classes.recipeName}>{recipeData.name}</Typography>
                <Typography className={classes.recipeIngredients}>{recipeData.ingredients}</Typography>
                <Typography className={classes.recipeInstructions}>{recipeData.instructions}</Typography>
            </Paper>
        )
    }
}

const styles = {
    root: {
        fontSize: "1.0rem",
        margin: "0px"
    },
    recipeName: {
        fontSize: "1.0rem",
        margin: "0px"
    },
    recipeIngredients: {
        fontSize: "1.0rem",
        margin: "0px"    },
    recipeInstructions: {
        fontSize: "1.0rem",
        margin: "0px"    }
};

withStyles(styles)(Recipe);

document.addEventListener('DOMContentLoaded', () => {
    ReactDOM.render(
        <App/>,
        document.body.appendChild(document.createElement('div')),
    )
});

【问题讨论】:

    标签: reactjs material-ui


    【解决方案1】:

    由于您没有将withStyles(styles)(Recipe); 设置为变量,我怀疑您必须在App 中直接使用Recipe

    withStyles 不会改变 RecipewithStyles 创建一个包装 Recipe 的新组件并将 classes 属性传递给它。为了看到 classes 属性,您需要使用新创建的组件,如下所示:

    const StyledRecipe = withStyles(styles)(Recipe);
    const App = ()=> {
       return <StyledRecipe/>;
    }
    

    【讨论】:

    • 我相信这是问题所在。如果可行,我将实施此解决方案并将其标记为解决方案。
    【解决方案2】:

    假设 App 是在一个单独的文件中定义的(对于可能来寻找这个问题的其他人),更改

    `withStyles(styles)(Recipe);`
    

    export default withStyles(styles)(Recipe);
    

    正如 Ryan 已经解释的那样,'withStyles 是创建和返回新组件的高阶组件'

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-12-11
      • 1970-01-01
      • 2021-09-06
      • 2020-06-21
      • 2019-11-21
      • 1970-01-01
      • 2018-02-14
      • 1970-01-01
      相关资源
      最近更新 更多