【问题标题】:Dynamically create nth-child selectors based on props to a Material-UI component根据 Material-UI 组件的 props 动态创建第 n 个子选择器
【发布时间】:2021-06-21 22:02:02
【问题描述】:

我正在尝试自定义 Material UI 滑块组件(特别是其 marks 属性)以显示 marks 数组中每个数据对象的出现次数。

基本上我希望滑块看起来像这样:

我是这样实现的:


const useStyles = makeStyles({
  root: {
    "& .MuiSlider-mark": {
      backgroundColor: "black",
      "&:nth-child(4)": {
        height: 8
      },
      "&:nth-child(6)": {
        height: 3
      },
      "&:nth-child(8)": {
        height: 5
      },
...
    },
  }
});

但我希望能够动态创建它。我可以将我的marks 属性传递给makeStyles,如下所示:const classes = useStyles(marks);,然后使用以下内容:

const useStyles = makeStyles({
  root: {
    "& .MuiSlider-mark": {
      backgroundColor: "black",
      "&:nth-child(4)": {
        height: (marks: {occurrences: number}[]) => marks[0
        ].occurrences
      },
      "&:nth-child(6)": {
        height: (marks: {occurrences: number}[]) => marks[1
        ].occurrences
      },
      "&:nth-child(8)": {
        height: (marks: {occurrences: number}[]) => marks[2
        ].occurrences
      },
...
    },

  }
});

这再次达到了预期的结果,但是如果我的marks 数组中有未知数量的对象怎么办?有没有办法动态生成nth-child 选择器?

我已经做了一个密码箱:https://codesandbox.io/s/percentage-slider-dynamic-marks-4o0m4?file=/src/DynamicMarks2.tsx

【问题讨论】:

    标签: javascript reactjs css-selectors material-ui


    【解决方案1】:

    我用以下代码管理它:

    const useStyles = makeStyles({
      root: (marks: { occurrences: number }[]) => {
        const marksReduce = marks.reduce((acc, cur, index) => {
          return {
            ...acc,
            [`&:nth-child(${4 + index * 2})`]: { height: cur.occurrences }
          };
        }, {});
    
        return {
          width: 200,
          "& .MuiSlider-mark": {
            backgroundColor: "black",
    
            ...marksReduce,
    
            [`&:nth-child(${4}n)`]: {
              height: marks[0].occurrences
            }
          },
          "& .MuiSlider-markLabel": {
            display: "none"
          }
        };
      }
    });
    
    Demo: https://codesandbox.io/s/percentage-slider-dynamic-marks-4o0m4?file=/src/DynamicMarks3.tsx
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-02-21
      • 2021-05-01
      • 2011-03-11
      • 1970-01-01
      • 2020-10-28
      • 1970-01-01
      相关资源
      最近更新 更多