Изменить css материала пользовательского интерфейса - PullRequest
2 голосов
/ 10 января 2020

У меня есть всплывающее окно с пользовательским интерфейсом, и я пытаюсь добавить к нему стиль в css.

Это мой поповер

    import React, { memo, useCallback } from 'react';
import PropTypes from 'prop-types';
import { makeStyles } from '@material-ui/styles';
import Grid from '@material-ui/core/Grid';
import Typography from '@material-ui/core/Typography';
import clsx from 'clsx';
import Popper from '@material-ui/core/Popper';
import gastronomia from 'assets/experiences/gastronomia.jpg';
import productos from 'assets/experiences/productos.jpg';
import giftcard from 'assets/experiences/giftcard.jpg';
import diversion from 'assets/experiences/diversion.jpg';
import deporte from 'assets/experiences/deporte.jpg';
import belleza from 'assets/experiences/belleza.jpg';
import gastronomiaExperiences from 'data/gastronomia';
import productosExperiences from 'data/productos';
import giftcardExperiences from 'data/giftcard';
import diversionExperiences from 'data/diversion';
import deporteExperiences from 'data/deporte';
import bellezaExperiences from 'data/belleza';


// Proptypes definitions to the component.
const propTypes = {
  /** Custom root className. */
  className: PropTypes.string,

};

// Default props definitions.
const defaultProps = {
  className: null,
};

// Component's styles
const useStyles = makeStyles(theme => ({
  root: {
    display: 'block',
    margin: '0 auto',
    maxWidth: '50%',
    [theme.breakpoints.down('md')]: {
      maxWidth: '70%',
    },
    [theme.breakpoints.down('sm')]: {
      maxWidth: '100%',
    },
    '& .experiences-column': {
      display: 'inline-block',
      verticalAlign: 'top',
      textAlign: 'center',
      '&.col1': {
        width: '36.31%',
        [theme.breakpoints.down('sm')]: {
          width: 'initial',
        },
      },
      '&.col2': {
        width: '63.69%',
        [theme.breakpoints.down('sm')]: {
          width: 'initial',
        },
      },
      '& .experience': {
        padding: 2,
        position: 'relative',
        '& img': {
          width: '100%',
          display: 'block',
        },
        '& .experience-title': {
          position: 'absolute',
          bottom: 30,
          left: 0,
          right: 0,
          textAlign: 'center',
        },
'& .deporte': {
        backgroundColor: '#000',
        '& img': {
          width: '30px',
          display: 'block',
        },
   },        
      },

paper: {
    border: '1px solid',
    padding: theme.spacing(1)

  },
    },
  },
}), { name: 'ExperiencesStyle' });


/**
 * Component used to render a grid of experiences.
 *
 * @param {object} props - The component's props.
 * @returns {object} React element.
 */
const Experiences = memo(


    const useCustomStylesByIds = ({ ids }) => {
  const myStyles = makeStyles(theme => {
    let stylesObj = {};

    ids.forEach(id => {
      stylesObj[getPaperKey(id)] = {
        backgroundColor: idToColorMapper[id]
      };
    });

    return stylesObj;
  });

  return myStyles();
};

const getPaperKey = id => `paper-${id}`;

const idToColorMapper = {
  gastronomia: "red",
  giftcard: "blue",
  deporte: "yellow",
  productos: "cyan",
  diversion: "green",
  belleza: "orange"
};

const ids = [
  "gastronomia",
  "giftcard",
  "deporte",
  "productos",
  "diversion",
  "belleza"
];

function SimplePoppers() {
  return ids.map(id => <CustomPopper key={id} id={id} />);
}

const CustomPopper = props => {
  const classes = useCustomStylesByIds({ ids });
  const [anchorEl, setAnchorEl] = React.useState(null);
  const { id } = props;
  const handleClick = event => {
    setAnchorEl(anchorEl ? null : event.currentTarget);
  };

  const open = Boolean(anchorEl);

    const experience = (img, title, id, popoverCategory) => (
      <div
        className="experience"
        aria-describedby={id}
        id={id}
        onClick={handleClick}
      >
        <img
          data-sizes="auto"
          className="lazyload"
          data-src={img}
          alt={title}
        />
        <div className="experience-title">
          <Typography
            color="textSecondary"
            variant="subtitle2"
            className="highlight highlight1"
            display="inline"
          >
            { title }
          </Typography>
        </div>

         <Popper
          id={id}
          open={anchorEl && anchorEl.id === id || false}
          anchorEl={anchorEl}
          className={id}
         >
          <div  className={classes[getPaperKey(id)]}>
            {
              popoverCategory.map(url => (
              <Grid 
              md={4}
              >
                <img
                  key={id}
                  data-sizes="auto"
                  className="lazyload"
                  src={url}
                  alt={ title }
                />
              </Grid>
              ))
            }
          </div>
        </Popper>
      </div>

    );

    console.log();
    return (

      <div className={clsx(classes.root, className)}>
        <div className="experiences-column col1">
          {experience(gastronomia, 'GASTRONOMÍA', 'gastronomia', gastronomiaExperiences)}
          {experience(giftcard, 'GIFT CARD', 'giftcard', giftcardExperiences)}
          {experience(deporte, 'DEPORTE', 'deporte', deporteExperiences)}
        </div>
        <div className="experiences-column col2">
          {experience(productos, 'PRODUCTOS', 'productos', productosExperiences)}
          {experience(diversion, 'DIVERSIÓN', 'diversion', diversionExperiences)}
          {experience(belleza, 'BELLEZA', 'belleza', bellezaExperiences)}
        </div>
      </div>

    );
  },
);

// Component proptypes.
Experiences.propTypes = propTypes;

// Component default props.
Experiences.defaultProps = defaultProps;

export default Experiences;

Я пытался добавить стиль в класс бумаги. но у меня нет результатов. Я хочу сделать фон другим цветом для каждого поповера и сделать ширину поповера одинаковой с родительским div. И переместите поповер вверх по опыту, которому он соответствует.

1 Ответ

4 голосов
/ 10 января 2020

Ответ обновлен на основе комментария автора


Вы можете присвоить каждому Popper специальное имя класса и динамически создавать эти классы, используя makeStyles. Допустим, ваши идентификаторы: «гестрономия», «подарочная карта», «депорта» (при условии, что у вас есть заранее идентификаторы. Если нет, вам нужно изменить мой ответ в соответствии с вашими потребностями) И скажем, вы хотите назвать ваши классы paper-gestronomy , paper-giftcard , paper-deporte :

import React from "react";
import { makeStyles } from "@material-ui/core/styles";
import Popper from "@material-ui/core/Popper";

const useCustomStylesByIds = ({ ids }) => {
  const myStyles = makeStyles(theme => {
    let stylesObj = {};

    ids.forEach(id => {
      stylesObj[getPaperKey(id)] = {
        backgroundColor: idToColorMapper[id]
      };
    });

    return stylesObj;
  });

  return myStyles();
};

const getPaperKey = id => `paper-${id}`;

const idToColorMapper = {
  gastronomia: "red",
  giftcard: "blue",
  deporte: "yellow",
  productos: "cyan",
  diversion: "green",
  belleza: "orange"
};

const ids = [
  "gastronomia",
  "giftcard",
  "deporte",
  "productos",
  "diversion",
  "belleza"
];

export default function SimplePoppers() {
  return ids.map(id => <CustomPopper key={id} id={id} />);
}

const CustomPopper = props => {
  const classes = useCustomStylesByIds({ ids });
  const [anchorEl, setAnchorEl] = React.useState(null);
  const { id } = props;
  const handleClick = event => {
    setAnchorEl(anchorEl ? null : event.currentTarget);
  };

  const open = Boolean(anchorEl);

  return (
    <div key={id}>
      <button aria-describedby={id} type="button" onClick={handleClick}>
        {id}
      </button>
      <Popper id={id} open={open} anchorEl={anchorEl}>
        <div className={classes[getPaperKey(id)]}>{id} with custom color</div>
      </Popper>
    </div>
  );
};

В В приведенном выше примере я обернул makeStyles своей собственной функцией, которая принимает идентификаторы в качестве аргументов и создает объект для каждого идентификатора. Пример возвращаемого объекта:

{
  'paper-gestronomy': {
    backgroundColor: 'red'
  },
  'paper-giftcard': {
    backgroundColor: 'blue'
  },
  'paper-deporte': {
    backgroundColor: 'yellow'
  }
}

Edit Invisible Backdrop

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...