将道具传递给 MUI 样式

新手上路,请多包涵

给定 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
},

我在网页上弄乱了组件卡样式。

顺便说一下,我通过 props 如下:

 <SimpleCard backgroundColor="#f5f2ff" />

请帮忙!

原文由 Diamond 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 558
2 个回答

这个答案是在 4.0 版之前写的,严重过时了!

说真的,如果您正在设计功能组件,请使用 makeStyles

James Tan 的答案是 4.x 版的最佳答案

这里下面的任何东西都是古老的:

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

请注意,在 Github 上存在一个请求此功能的 未解决问题,一些评论可能会为您指出您可能感兴趣的替代解决方案。

使用道具更改卡片背景颜色的一种方法是使用内联样式设置此属性。我已经对您的 原始代码框 进行了一些更改,您可以查看 修改后的版本 以查看此操作。

这是我所做的:

  1. 使用 backgroundColor 渲染组件:
 // in index.js
if (rootElement) {
  render(<Demo backgroundColor="#f00" />, rootElement);
}

  1. 使用此道具将内联样式应用于卡片:
     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 组件 具有红色 (#F00) 背景

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

原文由 Ken Gregory 发布,翻译遵循 CC BY-SA 4.0 许可协议

删除旧答案,因为它没有存在的理由。

这就是你想要的:

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

const useStyles = makeStyles({
    firstStyle: {
        backgroundColor: props => props.backgroundColor,
    },
    secondStyle: {
        color: props => props.color,
    },
});

const MyComponent = ({children, ...props}) =>{
    const { firstStyle, secondStyle } = useStyles(props);
    return(
        <div className={`${firstStyle} ${secondStyle}`}>
            {children}
        </div>
    )
}

export default MyComponent;

现在您可以像这样使用它:

 <MyComponent color="yellow" backgroundColor="purple">
    Well done
</MyComponent>

官方文档

原文由 James Tan 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进