首页 > 解决方案 > Material UI - 将道具应用于伪元素

问题描述

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

const useStyles = makeStyles({
  box: {
    '&::before': {
      content: props => `${props.text}` // should be props.text from <Child /> (i.e. '111')
    }
  }
});

function Parent() {
    return <Child text="111" />
}

function Child(props) {
    const { text } = props;
    const classes = useStyles({ text });
    return <Box className={classes.box} />
}

我怎样才能在外面使用道具<Child />?我已经尝试过数据属性,但也没有工作。似乎content在伪元素中与其他属性有点不同

标签: reactjsmaterial-ui

解决方案


您可以在 useStyles 调用中传递道具。

const classes = useStyles({text: 'asdf'})

您的样式定义中的用法是这样的

const useStyles = makeStyles({
  box: {
    '&::before': {
      content: (props) => `${props.text}`
    }
  }
});

推荐阅读