如何正确地将classNames传递给react-admin中的组件?

时间:2019-07-14 18:51:29

标签: reactjs jsx react-admin

我想将值传递给我的react admin中的组件,以便能够通过配置在我的Letter Avatar上设置颜色。

我能够传递值,但是由于某种原因className不接受它,并且将颜色保留为默认颜色。

我的配置文件:

export const SitesData = {
    1: {
        name: "E",
        bgcolor: "secondary",
        bgcolor2: "indigo",
    },
    2: {
        name: "A",
        bgcolor: "primary",
        bgcolor2: "purple",
    },
    3: {
        name: "H",
        bgcolor: "warning",
        bgcolor2: "orange",
    }
};

和我的代码:

export const SiteName2 = ({ record = {} }) => {
    const site = SitesData[parseInt(record.site_id)];

    return <MyAvatar source='site_id' sitename={site.name} bgcolor={site.bgcolor2} />;
};
import React from 'react';
import PropTypes from 'prop-types';
import pure from 'recompose/pure';
import Avatar from '@material-ui/core/Avatar';
import { withStyles } from '@material-ui/core/styles';
import deepOrange from '@material-ui/core/colors/deepOrange';
import deepPurple from '@material-ui/core/colors/deepPurple';
import indigo from '@material-ui/core/colors/indigo';
import green from '@material-ui/core/colors/green';
import classnames from 'classnames';

const styles = {
    orange: {
        margin: 4,
        color: '#fff',
        backgroundColor: deepOrange[500],
    },
    purple: {
        margin: 4,
        color: '#fff',
        backgroundColor: deepPurple[500],
    },
    indigo: {
        margin: 4,
        color: '#fff',
        backgroundColor: indigo[500],
    },
    green: {
        margin: 4,
        color: '#fff',
        backgroundColor: green[500],
    },
};

export const MyAvatar = ({
    className,
    classes = {},
    source,
    sitename,
    bgcolor,
    record = {},
}) => {
    var myClass = `classes.${bgcolor}`;
    console.log("AVATAR: ", myClass, bgcolor);
    return (
                <Avatar className={myClass}>{sitename}</Avatar>
    );
};

MyAvatar.propTypes = {
    className: PropTypes.string,
    classes: PropTypes.object,
    elStyle: PropTypes.object,
    sortBy: PropTypes.string,
    source: PropTypes.string.isRequired,
    record: PropTypes.object,
    sitename: PropTypes.string,
    bgcolor: PropTypes.string,
};

// wat? TypeScript looses the displayName if we don't set it explicitly
MyAvatar.displayName = 'MyAvatar';

const MyPureAvatar = withStyles(styles)(pure(MyAvatar));

export default MyPureAvatar;

不确定为什么myAvatar的类名不接受颜色,但是可以确定的问题是我如何将值传递给它(假设我试图为MyAvatar的className显式编写class.purple,并且可以正常工作。

1 个答案:

答案 0 :(得分:0)

事实证明,如果我这样将我的值传递给className

var myClass = classes[bgcolor];

代替此:

var myClass = `classes.${bgcolor}`;

classNames接受它,并且按预期工作