材质UI步进器4不同步长的4种不同连接器颜色

时间:2020-07-08 13:51:05

标签: reactjs material-ui frontend stepper react-material

我想知道是否可以在每个步骤中使用不同颜色的多种连接器颜色。因此,第一个连接器将是蓝色,然后是绿色,然后是黄色,然后是红色,同时保持先前的颜色不变。最接近的已将所有以前的颜色更改为相同的颜色。有没有办法保持以前的颜色相同?

我链接的示例仅具有一种颜色的连接器

Example of Stepper with Connector only one color

2 个答案:

答案 0 :(得分:0)

此答案显示了如何更改单个StepIcon的颜色

鉴于您在组件外部有一个函数,可渲染Stepper,该函数返回包含步骤标签及其相应图标颜色的数组:

function getStepLabels() {
  return [
    {
      label: "Select campaign settings",
      color: "red"
    },
    {
      label: "Create an ad group",
      color: "blue"
    },
    {
      label: "Create an ad",
      color: "green"
    }
  ];
}

您可以通过makeStyles函数使用material-ui的Hook API为每个标签图标生成类(如果您使用的是类组件,则可能需要看一下withStyles函数):

const useIconStyles = makeStyles(
  (() => {
    return getStepLabels().reduce((styles, step, index) => {
      styles[index] = { color: `${step.color} !important` };
      return styles;
    }, {});
  })()
);

并将生成的钩子添加到您的组件中:const iconClasses = useIconStyles();

渲染步进器时,您可以使用如下生成的类:

[...]

<Step key={label} {...stepProps}>
    <StepLabel
        {...labelProps}
         StepIconProps={{ classes: { root: iconClasses[index] } }}
    >
         {label}
    </StepLabel>
</Step>

[...]

这是一个可行的示例:

Edit serene-heyrovsky-bjo0e

答案 1 :(得分:0)

如果仔细查看Stepper组件的渲染输出,您会注意到StepLabelStepConnector是同级组件。这意味着您可以使用CSS :nth-child()伪类选择特定的连接器。如果要在第一步标签之后选择连接器,则可以使用选择器:nth-child(2)。对于第二步标签之后的连接器,它将为:nth-child(4)

如果您有一系列这样的步骤标签:

[
  {
    label: "First label",
    connectorColor: "red"
  },
  {
    label: "Second label",
    connectorColor: "green"
  },
  {
    label: "Third label"
  }
];

您可以将此数组传递到由makeStyles函数创建的material-ui样式挂钩,并动态生成为每个连接器设置样式所需的所有不同CSS选择器:

const useConnectorStyles = makeStyles({
  stepConnector: steps => {
    const styles = {};

    steps.forEach(({ connectorColor }, index) => {
      if (index < steps.length - 1) {
        styles[`&:nth-child(${2 * index + 2})`] = { color: connectorColor };
      }
    });

    return styles;
  },
  stepConnectorLine: {
    borderColor: "currentColor"
  }
});

现在在您的组件const connectorClasses = useConnectorStyles(stepLabels);中使用生成的样式挂钩,并为connector组件提供Stepper道具:

connector={
    <StepConnector
        classes={{
            root: connectorClasses.stepConnector,
            line: connectorClasses.stepConnectorLine
        }}
    />
}

这是一个可行的示例:

Edit silent-dream-xjlyz