首页 > 解决方案 > 带有样式类的常量变量在 reactjs 中不起作用

问题描述

我正在使用 react js 来创建一个带有卡片的界面。在这期间我遇到了一个问题,

我完全无法在我的代码中使用样式类

我在一个名为 card.js 的 js 文件中编写了代码来创建一些样式表类,代码如下所示。

import React from 'react';
const Color = {"default" : "#ffff","grey": "#808080"};
export const styles = theme=>({
    card:
    {
        width: "400px",
        height: "600px",
        backgroundColor: Color.default,
        borderRadius: "5px",
        border: "1px solid"+Color.grey,
    }
});

我已使用以下代码将导出的样式导入名为 activity.js 的文件中。

import React from 'react';
import {styles} from './card';
var Activity = (props)=>{
    return(
        <div>
            <h1 className={styles.card}>Card 1</h1>
            <h1 className={styles.card}>Card 2</h1>
        </div>
    );
}
export default Activity;

这里没有样式被添加到 h1 标签中。我被卡住了,请帮帮我。

标签: reactjsstyles

解决方案


可以选择使用“@material-ui/styles”中的withStyles函数。以下 URL 中显示的示例:

import React from 'react';
import PropTypes from 'prop-types';
import { withStyles } from '@material-ui/styles';
import Button from '@material-ui/core/Button';

const styles = {
  root: {
    background: 'linear-gradient(45deg, #FE6B8B 30%, #FF8E53 90%)',
    border: 0,
    borderRadius: 3,
    boxShadow: '0 3px 5px 2px rgba(255, 105, 135, .3)',
    color: 'white',
    height: 48,
    padding: '0 30px',
  },
};

function HigherOrderComponent(props) {
  const { classes } = props;
  return <Button className={classes.root}>Higher-order component</Button>;
}

HigherOrderComponent.propTypes = {
  classes: PropTypes.object.isRequired,
};

export default withStyles(styles)(HigherOrderComponent);

推荐阅读