javascript - 自定义组件不接受样式React Material ui

标签 javascript reactjs material-ui react-css-modules

我创建了一个Avatar 组件,它是一个非常基本的组件,显示图标和一些文本。这是该组件的代码。

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 样式,即,我想要 backgroundColorAvatar 组件变为红色,但这并没有发生,我正在使用 Material UI 。我的猜测是样式 Prop 没有正确传递到 Avatar 组件,或者我没有正确应用样式。

最佳答案

您正在将 AvatarDiv 作为 'className' 属性传递。您不会在此处应用该类,因为 AvatarDiv 是一个自定义组件。

  <AvatarProfile
          name={name}
          subtitle={subtitle}
          className={classes.AvatarDiv}

您必须将其作为 Prop 传递,并使用该 Prop 在子组件中应用样式。我在codesandbox中做了类似的事情,我将按钮的颜色更改为橙​​色并将其作为 Prop 传递给子组件。请检查-https://codesandbox.io/s/lyxz92m7nl

关于javascript - 自定义组件不接受样式React Material ui,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52042691/

相关文章:

javascript - 当所有字段都填满时启用按钮

reactjs - 继电器现代: delete record in optimisticUpdater

javascript - react jss 如何设置自定义 html 标签的样式

reactjs - material-ui reactjs中的嵌套抽屉

css - 如何在 JS 中使用 css 来实现嵌套悬停样式、Material UI

javascript - 如何测试 html5 音频、视频和特定的 css 属性?

javascript - 解析器阻塞与渲染阻塞

javascript - react 表行填充问题

javascript - 在 React I18next 中,首先初始化,显示 json key

reactjs - 在无状态组件中迭代子组件react/react-native