【问题标题】:Hover style '&:hover:{ }' doesn't work for the button within react component悬停样式 '&:hover:{ }' 不适用于反应组件中的按钮
【发布时间】:2019-04-14 04:40:25
【问题描述】:

这些天我正在使用 react 组件,并且在为我的一个按钮设置悬停样式时遇到了一些问题。以下是我在组件中使用的代码 sn-p。

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

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

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

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);

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

【问题讨论】:

标签: css reactjs react-component


【解决方案1】:

您不能在内联样式中利用 :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);

【讨论】:

    猜你喜欢
    • 2023-01-22
    • 2019-09-08
    • 2020-10-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-06
    相关资源
    最近更新 更多