我正在尝试使用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')),
)
});
答案 0 :(得分:3)
由于您没有将withStyles(styles)(Recipe);
设置为变量,因此我怀疑您必须直接在Recipe
中使用App
。
withStyles
不变Recipe
。 withStyles
创建一个包装Recipe
的新组件,并将classes
属性传递给它。为了查看classes
道具,您需要将新创建的组件与以下内容一起使用:
const StyledRecipe = withStyles(styles)(Recipe);
const App = ()=> {
return <StyledRecipe/>;
}
答案 1 :(得分:0)
假设App是在单独的文件中定义的(对于其他可能正在寻找此问题的人),请更改
`withStyles(styles)(Recipe);`
收件人
export default withStyles(styles)(Recipe);
正如Ryan所解释的那样,“ withStyles是创建并返回新组件的高阶组件”。