【问题标题】:React hover style not working when used with Radium and Material-UI与 Radium 和 Material-UI 一起使用时,React 悬停样式不起作用
【发布时间】:2019-05-18 21:40:00
【问题描述】:

我在 react 中使用 Radium 库进行内联样式。使用它可以很好地用于其他组件,但我遇到了 Material-UI 组件的问题。当我将鼠标悬停在 Paper 上时,它不会将颜色变为绿色。这里有什么问题?我该如何解决 ?

import React, { Component, Fragment } from 'react';
import { Grid, GridList, Paper, ListItem, List, ListItemIcon, ListItemText } from '@material-ui/core';
import { connect } from 'react-redux';
import Radium from 'radium';

class AchievementsHome extends Component {

    render() {

        return <>
            <Grid container alignItems="center" direction="column">
                <h1>Achievements</h1>

                <Paper
                style={{backgroundColor:'red' , ':hover':{backgroundColor:'green' }}
                 >
                   <h1>Hi</h1>
                </Paper>
            </Grid>
        </>
    }
}

const mapStateToProps = (state) => {
    return {
        achievements: state.achievements
    }
}

export default connect(mapStateToProps)(Radium(AchievementsHome)); 

【问题讨论】:

    标签: css reactjs react-redux material-ui radium


    【解决方案1】:

    使用 Material UI 外部样式(因此不直接来自 Material UI 库的样式)几乎不会起作用,要更改悬停时的颜色,您必须按照文档的Themes 部分中的说明设置主题

    首先获取导入 withStyles 并定义一个主题。

    import { withStyles } from "@material-ui/core/styles";
    
    
    const customStyles = theme => ({
      root: {
        backgroundColor: "red",
        "&:hover": {
          backgroundColor: "green"
        }
      }
    });
    

    比定义一个用 withStyles 包裹的新组件:

    const CustomPaper = withStyles(customStyles)(Paper);
    

    在你的渲染中使用你定义的组件:

         <CustomPaper
         />
    

    希望这会有所帮助。

    【讨论】:

    • 请给出与我上面显示的代码相关的代码。
    • 并解释您与镭相关的解决方案
    • 就像我提到的那样,Material UI 在大多数情况下不能与 Radium 等外部样式库一起使用,我已经编辑了答案以匹配您的特定代码。
    • 它还支持哪些其他伪选择器?我浏览了您发送的链接,没有提到此类选择器或“悬停”。如果您知道,请重定向到包含该信息的链接。
    【解决方案2】:

    Material UI provides its own way of styling using CSS in JS (JSS). 它提供了一个withStyles 高阶组件和一个withTheme,让您可以在全局主题级别进行样式设置。您还可以为某些组件传递类名以进行自定义样式。

    您不需要使用 Radium 来设置 Material UI 组件的样式。

    您的悬停 CSS 选择器也需要包含父 CSS 选择器:

    const paperStyle = {
      backgroundColor: 'red',
      '&:hover': {
        backgroundColor: 'green'
      }
    }
    
    return (
      <Paper styles={paperStyle}>
        <Typography variant="h1">Hi</Typography>
      </Paper>
    );
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-10-27
      • 2020-07-10
      • 2020-06-12
      • 2019-09-01
      • 1970-01-01
      • 2020-06-16
      • 2022-06-22
      相关资源
      最近更新 更多