点击物料UI<按钮更改波纹颜色/>

2022-02-22 00:00:00 reactjs javascript material-ui

这是我的<MyButton />组件

import React from 'react';
import { withStyles } from '@material-ui/core/styles';
import Button from '@material-ui/core/Button';

const styles = theme => ({
  button: {
    backgroundColor: 'green',
    "&:hover": {
      backgroundColor: "red"
    },
  },
});

function MyButton(props) {

  return (
    <Button
      className={props.classes.button} >
      {props.text}
    </Button>
  );
}

export default withStyles(styles)(MyButton);
目前,按钮上有默认的单击效果,在单击时使其变亮/变亮(参见此处:https://material-ui.com/demos/buttons/)。但是,当单击按钮时,我希望"涟漪"的颜色为blue

我已尝试

"&:click": {
    backgroundColor: "blue"
},

"&:active": {
    backgroundColor: "blue"
},

不过运气不好。单击按钮时如何更改波纹的颜色?


解决方案

这里有一个示例,说明如何修改v4的按钮波纹(v5示例进一步向下):

import React from "react";
import { withStyles } from "@material-ui/core/styles";
import Button from "@material-ui/core/Button";

const styles = theme => ({
  button: {
    backgroundColor: "green",
    "&:hover": {
      backgroundColor: "red"
    }
  },
  child: {
    backgroundColor: "blue"
  },
  rippleVisible: {
    opacity: 0.5,
    animation: `$enter 550ms ${theme.transitions.easing.easeInOut}`
  },
  "@keyframes enter": {
    "0%": {
      transform: "scale(0)",
      opacity: 0.1
    },
    "100%": {
      transform: "scale(1)",
      opacity: 0.5
    }
  }
});

function MyButton({ classes, ...other }) {
  const { button: buttonClass, ...rippleClasses } = classes;
  return (
    <Button
      TouchRippleProps={{ classes: rippleClasses }}
      className={buttonClass}
      {...other}
    />
  );
}

export default withStyles(styles)(MyButton);

涟漪的默认不透明度为0.3。在本例中,我将其增加到0.5,以便更容易验证涟漪是否为蓝色。由于按钮背景为红色(由于悬停样式),因此结果为紫色。如果通过键盘移动到按钮,您将获得不同的整体效果,因为蓝色将位于按钮的绿色背景之上。

您可以在我的回答中找到一些额外的背景信息:How to set MuiButton text and active color

设计涟漪样式的主要资源是其源代码:https://github.com/mui-org/material-ui/blob/v4.10.2/packages/material-ui/src/ButtonBase/TouchRipple.js

JSS关键帧文档:https://cssinjs.org/jss-syntax/?v=v10.3.0#keyframes-animation


这里有一个类似的MUI v5示例:

import { styled } from "@mui/material/styles";
import Button from "@mui/material/Button";
import { keyframes } from "@emotion/react";

const enterKeyframe = keyframes`
  0% {
    transform: scale(0);
    opacity: 0.1;
  }
  100% {
    transform: scale(1);
    opacity: 0.5;
  }
`;
const StyledButton = styled(Button)`
  background-color: green;
  &:hover {
    background-color: red;
  }
  && .MuiTouchRipple-child {
    background-color: blue;
  }
  && .MuiTouchRipple-rippleVisible {
    opacity: 0.5;
    animation-name: ${enterKeyframe};
    animation-duration: 550ms;
    animation-timing-function: ${({ theme }) =>
      theme.transitions.easing.easeInOut};
  }
`;
export default StyledButton;

v5 TouchRipple源代码:https://github.com/mui/material-ui/blob/v5.4.0/packages/mui-material/src/ButtonBase/TouchRipple.js#L92

情感关键帧文档:https://emotion.sh/docs/keyframes

演示使用关键帧的答案:How to apply custom animation effect @keyframes in MUI?

相关文章