简体   繁体   English

如何在 material-ui 组件上设置 HTML 元素 ID?

[英]How to set a HTML element ID on a material-ui component?

I have a website built with Gatsby.js using the Material-UI .我有一个使用Material-UI使用 Gatsby.js 构建的网站。

Specific problem is this: I want to use the Google Tag Manager "Element Visibility" triggers.具体问题是:我想使用 Google 标签管理器的“元素可见性”触发器。 If some HTML element becomes visible, GTM should fire some GA tag.如果某些 HTML 元素变得可见,GTM 应该触发某些 GA 标记。

Question is this: how can I specify the HTML ID for a material-ui component for GTM (or anything else) to find it?问题是:如何为 GTM(或其他任何东西)的 material-ui 组件指定 HTML ID 以找到它?

First example:第一个例子:

// ...react imports omitted...
import makeStyles from '@material-ui/core/styles/makeStyles';
import Box from '@material-ui/core/Box';
import Grid from '@material-ui/core/Grid';
import CloseIcon from '@material-ui/icons/Close';

import Link from '~components/Link';
import ButtonSubmit from '~components/form-buttons/ButtonSubmit';
import Container from '~components/Container';

// ... all other imports are in-house code

const useStyles = makeStyles(theme => ({ /* ...styles... */}));

const GuestUserSoftSaleSecondPopup = ({ which, ...rest }) => {
  const classes = useStyles();

  // ...setup code omitted...

  return (
    <Box bgcolor="#474d5c" width="100%" py={4} className={classes.banner}>
      <Container>
        <Grid container direction="row" justify="space-between" alignItems="center" spacing={2}>
          <Grid item xs={12} sm={1} md={3} lg={4}>
            <CloseIcon onClick={handleClose} size="large" className={classes.closeIcon} />
          </Grid>

          <Grid item xs={12} sm={7} md={5} lg={4}>
            <Link to="/subscribe" variant="h5" className={classes.linkStyle}>
              Become a member for full access
            </Link>
          </Grid>
          <Grid item xs={12} sm={4} className={classes.buttonPosition}>
            <Link to="/subscribe" underline="none" className={classes.linkStyle}>
              <ButtonSubmit type="button" fullWidth={false}>
                See my option
              </ButtonSubmit>
            </Link>
          </Grid>
        </Grid>
      </Container>
    </Box>
  );
};
// ...proptypes and `export` clause

Second example:第二个例子:

// ...react imports omitted...
import makeStyles from '@material-ui/core/styles/makeStyles';
import MuiDialog from '@material-ui/core/Dialog';

const useStyles = makeStyles(() => ({ /* ...styles... */ }));

const Dialog = ({ children, background, backdrop, isOpen, ...rest }) => {
  const classes = useStyles({ background });
  return (
    <MuiDialog
      open={isOpen}
      maxWidth="sm"
      fullWidth
      disableBackdropClick
      disableEscapeKeyDown
      BackdropProps={{
        className: backdrop ? classes.backdropBM : classes.backdrop
      }}
      PaperProps={{
        className: classes.paper
      }}
      scroll="body"
      {...rest}
    >
      {children}
    </MuiDialog>
  );
};

If you look at the API documentation for almost any of the Material-UI components, you will find at the end of the "Props" section a statement like the following example from Dialog :如果您查看几乎所有 Material-UI 组件的 API 文档,您会在“道具”部分的末尾找到类似以下Dialog示例的语句:

Any other props supplied will be provided to the root element (Modal).提供的任何其他道具都将提供给根元素(模态)。

This means that any props not explicitly recognized by this component will be passed along eventually to whatever HTML element is the outermost element rendered.这意味着任何未被该组件明确识别的 props 最终都会传递给渲染的最外层元素的任何 HTML 元素。 So for most Material-UI components, in order to add an id property, you just specify it.所以对于大多数 Material-UI 组件,为了添加一个id属性,你只需指定它。

My example below (a modification of the Simple Dialog demo ) includes three different ids: one on the Dialog element which will be placed on the outermost div of the Modal , one specified via the PaperProps which will go on the main Paper div of the visible content of the dialog, and one on the Box wrapped around the dialog content.我下面的示例(对Simple Dialog 演示的修改)包括三个不同的 id:一个在Dialog元素上,它将放置在Modal的最外层div上,一个通过PaperProps指定,它将放在可见的主要Paper div上对话框的内容,以及环绕对话框内容的Box上的一个。

import React from "react";
import PropTypes from "prop-types";
import { makeStyles } from "@material-ui/core/styles";
import Button from "@material-ui/core/Button";
import Avatar from "@material-ui/core/Avatar";
import List from "@material-ui/core/List";
import ListItem from "@material-ui/core/ListItem";
import ListItemAvatar from "@material-ui/core/ListItemAvatar";
import ListItemText from "@material-ui/core/ListItemText";
import DialogTitle from "@material-ui/core/DialogTitle";
import Dialog from "@material-ui/core/Dialog";
import PersonIcon from "@material-ui/icons/Person";
import Typography from "@material-ui/core/Typography";
import { blue } from "@material-ui/core/colors";
import Box from "@material-ui/core/Box";

const emails = ["username@gmail.com", "user02@gmail.com"];
const useStyles = makeStyles({
  avatar: {
    backgroundColor: blue[100],
    color: blue[600]
  }
});

function SimpleDialog(props) {
  const classes = useStyles();
  const { onClose, selectedValue, open } = props;

  const handleClose = () => {
    onClose(selectedValue);
  };

  const handleListItemClick = value => {
    onClose(value);
  };

  return (
    <Dialog
      onClose={handleClose}
      aria-labelledby="simple-dialog-title"
      open={open}
      PaperProps={{ id: "MyDialogPaperID" }}
      id="ThisIDWillBeOnTheModal"
    >
      <DialogTitle id="simple-dialog-title">Set backup account</DialogTitle>
      <Box id="MyBoxID">
        <List>
          {emails.map(email => (
            <ListItem
              button
              onClick={() => handleListItemClick(email)}
              key={email}
            >
              <ListItemAvatar>
                <Avatar className={classes.avatar}>
                  <PersonIcon />
                </Avatar>
              </ListItemAvatar>
              <ListItemText primary={email} />
            </ListItem>
          ))}
        </List>
      </Box>
    </Dialog>
  );
}

SimpleDialog.propTypes = {
  onClose: PropTypes.func.isRequired,
  open: PropTypes.bool.isRequired,
  selectedValue: PropTypes.string.isRequired
};

export default function SimpleDialogDemo() {
  const [open, setOpen] = React.useState(false);
  const [selectedValue, setSelectedValue] = React.useState(emails[1]);

  const handleClickOpen = () => {
    setOpen(true);
  };

  const handleClose = value => {
    setOpen(false);
    setSelectedValue(value);
  };

  return (
    <div>
      <Typography variant="subtitle1">Selected: {selectedValue}</Typography>
      <br />
      <Button variant="outlined" color="primary" onClick={handleClickOpen}>
        Open simple dialog
      </Button>
      <SimpleDialog
        selectedValue={selectedValue}
        open={open}
        onClose={handleClose}
      />
    </div>
  );
}

在对话框、纸张和框上编辑 id

Material UI components don't let you set an id for them since the implementation inside should be a black box and may contain multiple html element. Material UI 组件不允许您为它们设置 id,因为内部的实现应该是一个黑盒子,并且可能包含多个 html 元素。 See if you can wrap the element in a div and put the id on that instead.看看是否可以将元素包装在 div 中,然后将 id 放在上面。

Another option would be to add a class (via the classes prop) to the element instead but I'm not sure if Google Tag Manager can use those instead of ids.另一种选择是向元素添加一个类(通过classes道具),但我不确定 Google 标签管理器是否可以使用这些而不是 id。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM