代码之家  ›  专栏  ›  技术社区  ›  Natesh bhat

与镭和材质UI一起使用时,反应悬停样式不起作用

  •  0
  • Natesh bhat  · 技术社区  · 7 年前

    我在react中使用Radium库进行内联样式设置。使用它可以很好地用于其他组件,但我对材质UI组件有问题。当我将鼠标悬停在纸上时,它不会将颜色更改为绿色。这里怎么了?我该如何解决这个问题?

    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)); 
    
    2 回复  |  直到 7 年前
        1
  •  4
  •   Dmitriy    7 年前

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

    首先用样式获取导入并定义一个主题。

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

    然后定义一个新组件,该组件使用以下样式进行包装:

    const CustomPaper = withStyles(customStyles)(Paper);
    

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

         <CustomPaper
         />
    

    希望这有帮助。

        2
  •  2
  •   user9903 user9903    7 年前

    Material UI provides its own way of styling using CSS in JS (JSS). 它提供了一个 withStyles 高阶分量与a withTheme

    您不需要使用镭来设置材质UI组件的样式。

    此外,用于悬停的CSS选择器需要包括父CSS选择器:

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