代码之家  ›  专栏  ›  技术社区  ›  JS3

如何将鼠标悬停在此按钮样式上?

  •  0
  • JS3  · 技术社区  · 5 年前

    这些是我的按钮代码。不知何故,只有当我在按钮本身中声明样式时,背景颜色才有效。在const useStyles中声明背景颜色不起作用,因此,我只做了这个。当背景颜色悬停在其上时,我如何对其进行编码?

    <Button
          variant="contained"
          {...otherProps}
          className={classes.margin}
          style={{ backgroundColor: " #e31837" }}
        >
          {children}
        </Button>
    
    0 回复  |  直到 5 年前
        1
  •  1
  •   buzatto    5 年前

    您可以使用root属性更改按钮样式( docs ),并在悬停时更改其背景:

    const useStyles = makeStyles((theme) => ({
      root: {
          backgroundColor: 'red',
          '&:hover': {
            backgroundColor: 'blue'
          }
      }
    }));
    
    
    <Button
          variant="contained"
          {...otherProps}
          className={classes.root}
          style={{ backgroundColor: " #e31837" }}
        >
          {children}
        </Button>
    
        2
  •  1
  •   Tom    5 年前

    您可以将其添加到样式中:

    '&:hover': {
        backgroundColor: ‘red’
    }
    
        3
  •  1
  •   Chris Kirby    5 年前
    <Button
          variant="contained"
          {...otherProps}
          className={classes.margin}
          onMouseOver={this.toggleHover} 
          onMouseOut={this.toggleHover} 
          style={btnStyle}
        >
          {children}
    </Button>
    

    然后添加一个切换悬停功能

    toggleHover(){
        this.setState({hover: !this.state.hover})
    }
    

    最后,在渲染函数上将样式设置为变量

    let btnStyle = {'backgroundColor: #e31837'};
    if (this.state.hover) {
        btnStyle = {'backgroundColor: #000000'}
    }
    
        4
  •  1
  •   reachtokish    5 年前

    您可以参考以下代码片段

    import React from 'react';
    import { createMuiTheme, withStyles, makeStyles, ThemeProvider } from '@material-ui/core/styles';
    import Button from '@material-ui/core/Button';
    import { green, purple } from '@material-ui/core/colors';
    
    const ColorButton = withStyles((theme) => ({
      root: {
        color: theme.palette.getContrastText(purple[500]),
        backgroundColor: purple[500],
        '&:hover': {
          backgroundColor: purple[700],
        },
      },
    }))(Button);
    
    export default function CustomizedButtons() {
      const classes = useStyles();
    
      return (
        <div>
          <ColorButton variant="contained" color="primary" className={classes.margin}>
            Custom CSS
          </ColorButton>
        </div>
      )
    }