【发布时间】:2019-02-02 04:35:32
【问题描述】:
我创建了一个Avatar Component,它是一个非常基本的组件,显示一个图标和一些文本。这是组件的代码。
import React from "react";
import PropTypes from "prop-types";
import { withStyles, Avatar, Typography } from "@material-ui/core";
import avatar_placeholder from "../images/avatar_man.svg";
const styles = theme => ({
row: {
display: "flex",
flexDirection: "row",
alignItems: "center"
},
avatar: {
width: 50,
height: 50,
marginRight: "2%"
},
subtitle: {
opacity: 0.5
}
});
const customAvatar = props => {
const { classes, name, subtitle } = props;
return (
<div className={classes.row}>
<Avatar alt={name} src={avatar_placeholder} />
<div>
<Typography variant="title">{name}</Typography>
<Typography variant="body2" className={classes.subtitle}>
{subtitle}
</Typography>
</div>
</div>
);
};
customAvatar.propTypes = {
classes: PropTypes.object.isRequired,
name: PropTypes.string.isRequired,
image: PropTypes.string,
subtitle: PropTypes.string
};
customAvatar.defaultProps = {
name: "John Doe",
subtitle: ""
};
export default withStyles(styles)(customAvatar);
Avatar组件是父组件的子组件,后面的代码是Avatar组件在父组件中的使用方式。
import React from "react";
import PropTypes from "prop-types";
import {
withStyles,
Card,
CardContent
} from "@material-ui/core";
import AvatarProfile from "./AvatarProfile";
const styles = {
cardContent: {
},
AvatarDiv: {
backgroundColor: "red"
}
};
const ItemCardWithCheckbox = props => {
const { classes, name, subtitle } = props;
return (
<Card>
<CardContent className={classes.cardContent}>
<AvatarProfile
name={name}
subtitle={subtitle}
className={classes.AvatarDiv}
/>
</CardContent>
</Card>
);
};
ItemCardWithCheckbox.propTypes = {
classes: PropTypes.object.isRequired
};
export default withStyles(styles)(ItemCardWithCheckbox);
如您所见,我正在尝试为Avatar 组件应用AvatarDiv 样式,即,我希望Avatar 组件的backgroundColor 为红色,但这没有发生,我正在使用@ 987654321@。我的猜测是样式道具没有正确传递给Avatar 组件,或者我没有正确应用样式。
【问题讨论】:
-
classes.AvatarDiv来自哪里?我看到它是styles对象的属性.. -
分享你的 `AvatarProfile' 组件。
-
@SakhiManso 或
customAvatar组件是AvatarProfile -
@ArupRakshit 差不多了,他们样式对象是用来设置该组件中所有内容的样式,为简洁起见,我跳过了
classes.cardContent的样式,但所有写在cardContent中的样式都是正确应用。
标签: javascript reactjs material-ui react-css-modules