悬停样式 '&:hover:{ }' 不适用于反应组件中的按钮

San*_*nee 4 css reactjs react-component

这些天我正在使用反应组件,并且在使用悬停样式设计我的一个按钮时遇到了一些问题。以下是我在组件中使用的代码片段。

const darkTheme = createMuiTheme({
    palette: {
        type: 'dark',
        secondary:amber
    },
    typography: {
        useNextVariants: true,
    }
});

const lightTheme = createMuiTheme({
    palette: {
        type: 'light',
        secondary:amber
    },
    typography: {
        useNextVariants: true,
    }
});
Run Code Online (Sandbox Code Playgroud)

上面是我正在使用的自定义主题。

class APIWidget extends Widget {

constructor(props) {
    super(props);

    this.styles = {
        button: {
            backgroundColor: amber[500],
            '&:hover': {
                backgroundColor: amber[700],
            },
            position: 'absolute',
            bottom: 20,
            right: 20
        },
    };
}

render() {
    return (
        <MuiThemeProvider theme={this.props.muiTheme.name === 'dark' ? darkTheme : lightTheme}>
                <Button variant="contained" color="secondary" style={this.styles.button}>
                    <ArrowBack style={{marginRight:15}}/>
                Back
                </Button>
        </MuiThemeProvider>
    );
}
}
global.dashboard.registerWidget('APIWidget', APIWidget);
Run Code Online (Sandbox Code Playgroud)

我正在使用 Material ui,并从中导入颜色。我的按钮背景颜色有效,而悬停颜色不起作用。您能否指出我的代码中是否有任何错误或建议任何方法来获得必要的悬停颜色。提前致谢。

Rya*_*ell 6

您不能利用伪类,例如:hover内联样式中的伪类。相反,样式需要位于 CSS 类中。withStyles下面是一个用于生成 CSS 类的示例(基于您的 APIWidget 类) 。

import {
  createMuiTheme,
  MuiThemeProvider,
  withStyles
} from "@material-ui/core/styles";
import Button from "@material-ui/core/Button";
import amber from "@material-ui/core/colors/amber";
import blue from "@material-ui/core/colors/blue";
import React from "react";
import ArrowBack from "@material-ui/icons/ArrowBack";

const darkTheme = createMuiTheme({
  palette: {
    type: "dark",
    primary: amber,
    secondary: blue
  }
});
const styles = (theme) => ({
  button: {
    backgroundColor: "red",
    "&:hover": {
      backgroundColor: "blue"
    },
    position: "absolute",
    bottom: 20,
    right: 20
  }
});

class APIWidget extends React.Component {
  render() {
    return (
      <MuiThemeProvider theme={darkTheme}>
        <Button
          variant="contained"
          color="secondary"
          className={this.props.classes.button}
          startIcon={<ArrowBack />}
        >
          Back
        </Button>
      </MuiThemeProvider>
    );
  }
}
export default withStyles(styles)(APIWidget);
Run Code Online (Sandbox Code Playgroud)

编辑按钮悬停颜色