1

我在 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)); 
4

2 回答 2

4

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

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

import { withStyles } from "@material-ui/core/styles";


const customStyles = theme => ({
  root: {
    backgroundColor: "red",
    "&:hover": {
      backgroundColor: "green"
    }
  }
});

然后定义一个用 withStyles 包装的新组件:

const CustomPaper = withStyles(customStyles)(Paper);

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

     <CustomPaper
     />

希望这可以帮助。

于 2018-12-18T13:26:54.817 回答
2

Material UI 使用 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>
);
于 2018-12-18T16:06:26.190 回答