将道具传递给素材UI样式

时间:2018-02-20 06:58:27

标签: reactjs material-ui

如下所示给出卡片代码:card

如何从

更新卡片样式或任何材质UI样式
    const styles = theme => ({
    card: {
    minWidth: 275,
  },

如下:

    const styles = theme => ({
    card: {
    minWidth: 275, backgroundColor: props.color  },

当我尝试最新版本时,我得到了

 Line 15:  'props' is not defined  no-undef

当我更新代码时:

const styles = theme =>  (props) => ({
    card: {
    minWidth: 275, backgroundColor: props.color  },

 const styles  = (theme ,props) => ({
        card: {
        minWidth: 275, backgroundColor: props.color  },

而不是

const styles = theme => ({
    card: {
    minWidth: 275, backgroundColor: props.color  },

我在网页上看到了组件卡样式。

顺便说一下,我按照以下方式传递道具:

<SimpleCard backgroundColor="#f5f2ff" />

请帮忙!

10 个答案:

答案 0 :(得分:23)

在材料ui中如何同时使用道具和主题的解决方案:

const useStyles = props => makeStyles( theme => ({
    div: {
        width: theme.spacing(props.units || 0)  
    }
}));

export default function ComponentExample({ children, ...props }){
    const { div } = useStyles(props)();
    return (
        <div className={div}>{children}</div>
    );
}

答案 1 :(得分:16)

以下是 Typescript 解决方案:

import React from 'react';
import { makeStyles } from '@material-ui/core/styles';
import Button from '@material-ui/core/Button';
import {Theme} from '@material-ui/core';

export interface StyleProps {
    height: number;
}

const useStyles = makeStyles<Theme, StyleProps>(theme => ({
  root: {
    background: 'green',
    height: ({height}) => height,
  },
}));

export default function Hook() {

  const props = {
    height: 48
  }

  const classes = useStyles(props);
  return <Button className={classes.root}>Styled with Hook API</Button>;
}

如果要使用它,请在this CodeSandbox

中尝试

答案 2 :(得分:15)

这就是你想要的。

import * as React from 'react';
import { withStyles } from '@material-ui/core';

const Content = props => {
    const styles = theme => ({
        content:{
            "background-color" : props.backgroundColor
        }
    });
    const div = props => (
        <div className={props.classes.content}>
            {props.children}
        </div>
    );
    const Styled = withStyles(styles)(div);
    return (
        <Styled>{props.children}</Styled>
    );
}

export default Content;

然后您可以像这样使用它:

<Content backgroundColor="#FAFAFA">
  Well done
</Content>

请记住像下面那样制作一个类组件,否则在重新渲染时会失去焦点。

import * as React from 'react';
import { withStyles } from '@material-ui/core';

class Content extends React.Component{
    styles = theme => ({
        content:{
            "padding" : this.props.padding,
            "min-height" : "100vh",
            "background-color" : this.props.backgroundColor
        }
    })

    div = props => (
        <div className={props.classes.content}>
            {props.children}
        </div>
    );
    
    Styled = withStyles(this.styles)(this.div);

    render(){
        return(
            <this.Styled>{this.props.children}</this.Styled>
        );
    }
}

export default Content;

答案 3 :(得分:8)

当您使用withStyles时,您可以访问theme,但不能访问props

请注意,Github上有一个open issue请求此功能,而且有些评论可能会指向您可能感兴趣的替代解决方案。

使用道具更改卡片背景颜色的一种方法是使用内联样式设置此属性。我已经对您的original codesandbox进行了一些更改,您可以查看modified version以查看此操作。

这就是我的所作所为:

  1. 使用backgroundColor prop:
  2. 渲染组件
    // in index.js
    if (rootElement) {
      render(<Demo backgroundColor="#f00" />, rootElement);
    }
    
    1. 使用此道具将内联样式应用于卡片:
    2.     function SimpleCard(props) {
            // in demo.js
            const { classes, backgroundColor } = props;
            const bull = <span className={classes.bullet}>•</span>;
            return (
              <div>
                <Card className={classes.card} style={{ backgroundColor }}>
                  <CardContent>
                    // etc
      

      现在渲染的Card component有一个红色(#F00)背景

      请查看文档的Overrides部分以了解其他选项。

答案 4 :(得分:7)

现在可以使用@material-ui/styles(在撰写本文时仍为alpha)来完成此操作,它提供类似于样式化组件的语法:

import React from "react";
import { makeStyles } from "@material-ui/styles";
import Button from "@material-ui/core/Button";

const useStyles = makeStyles({
  root: {
    background: props => props.color,
    "&:hover": {
      background: props => props.hover
    }
  }
});

export function MyButton(props) {
  const classes = useStyles(props);
  return <Button className={classes.root}>My Button</Button>;
}

使用JSX:<MyButton color="red" hover="blue" />

此代码改编自使用makeStyles的{​​{3}},但其他Material-UI API styledwithStyles({{3 }}。

the demo关闭example

答案 5 :(得分:2)

我花了几个小时试图让 withStyles 处理在 Typescript 中传递的属性。我在网上找到的所有解决方案都不适合我尝试做的事情,所以我最终将自己的解决方案编织在一起,并使用了一些片段。

如果您有来自 Material UI 的外部组件,您想要提供默认样式,但您还希望通过将不同的样式选项传递给组件来重用它,那么这应该可以工作:

import * as React from 'react';
import { Theme, createStyles, makeStyles } from '@material-ui/core/styles';
import { TableCell, TableCellProps } from '@material-ui/core';

type Props = {
    backgroundColor?: string
}

const useStyles = makeStyles<Theme, Props>(theme =>
    createStyles({
        head: {
            backgroundColor: ({ backgroundColor }) => backgroundColor || theme.palette.common.black,
            color: theme.palette.common.white,
            fontSize: 13
        },
        body: {
            fontSize: 12,
        },
    })
);

export function StyledTableCell(props: Props & Omit<TableCellProps, keyof Props>) {
    const classes = useStyles(props);
    return <TableCell classes={classes} {...props} />;
}

这可能不是完美的解决方案,但它似乎有效。他们不只是修改 withStyles 以接受属性,这真是个麻烦事。这会让事情变得容易很多。

答案 6 :(得分:1)

带有类组件的 TypeScript 解决方案:

type PropsBeforeStyle = {
  propA: string;
  propB: number;
}

const styles = (theme: Theme) => createStyles({
  root: {
    color: (props: PropsBeforeStyle) => {}
  }
});

type Props = PropsBeforeStyle & WithStyles<typeof styles>;

class MyClassComponent extends Component<Props> {...}

export default withStyles(styles)(MyClassComponent);

答案 7 :(得分:1)

此线程中缺少 props 中的 withStyles 使用(并导致认为它不受支持)

但这对我有用(比如为 MenuItem 设置样式):

const StyledMenuItem = withStyles((theme) => ({
 root: {
  '&:focus': {
    backgroundColor: props => props.focusBackground,
    '& .MuiListItemIcon-root, & .MuiListItemText-primary': {
      color: props => props.focusColor,
    },
  },
},

}))(MenuItem);

然后使用它:

 <StyledMenuItem focusColor={'red'} focusBackground={'green'}... >...</StyledMenuItem>

答案 8 :(得分:0)

import React from "react";
import { makeStyles } from "@material-ui/styles";
import Button from "@material-ui/core/Button";

const useStyles = makeStyles({
  root: {
    background: props => props.color,
    "&:hover": {
      background: props => props.hover
    }
  }
});

export function MyButton(props) {
  const classes = useStyles({color: 'red', hover: 'green'});
  return <Button className={classes.root}>My Button</Button>;
}

答案 9 :(得分:0)

export const renderButton = (tag, method, color) => {
  const OkButton = withStyles({
    root: {
      "color": `${color}`,
      "filter": "opacity(0.5)",
      "textShadow": "0 0 3px #24fda39a",
      "backgroundColor": "none",
      "borderRadius": "2px solid #24fda3c9",
      "outline": "none",
      "border": "2px solid #24fda3c9",
      "&:hover": {
        color: "#24fda3c9",
        border: "2px solid #24fda3c9",
        filter: "opacity(1)",
      },
      "&:active": {
        outline: "none",
      },
      "&:focus": {
        outline: "none",
      },
    },
  })(Button);
  return (
    <OkButton tag={tag} color={color} fullWidth onClick={method}>
      {tag}
    </OkButton>
  );
};

renderButton('Submit', toggleAlert, 'red')

相关问题