将道具传递给素材UI样式

Dia*_*ond 24 reactjs material-ui

给出如下卡片代码: 卡片

如何更新卡片样式或任何材质UI样式

    const styles = theme => ({
    card: {
    minWidth: 275,
  },
Run Code Online (Sandbox Code Playgroud)

如下:

    const styles = theme => ({
    card: {
    minWidth: 275, backgroundColor: props.color  },
Run Code Online (Sandbox Code Playgroud)

当我尝试最新的那个时,我得到了

 Line 15:  'props' is not defined  no-undef
Run Code Online (Sandbox Code Playgroud)

当我更新代码时:

const styles = theme =>  (props) => ({
    card: {
    minWidth: 275, backgroundColor: props.color  },
Run Code Online (Sandbox Code Playgroud)

 const styles  = (theme ,props) => ({
        card: {
        minWidth: 275, backgroundColor: props.color  },
Run Code Online (Sandbox Code Playgroud)

代替

const styles = theme => ({
    card: {
    minWidth: 275, backgroundColor: props.color  },
Run Code Online (Sandbox Code Playgroud)

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

顺便说一句,我传递道具如下:

<SimpleCard backgroundColor="#f5f2ff" />
Run Code Online (Sandbox Code Playgroud)

请帮忙!

Nea*_*arl 56

MUI v5中,这是在创建样式对象时使用以下方法访问 props 的方式styled()

import { styled } from "@mui/material";

const StyledBox = styled(Box)(({ theme, myColor }) => ({
  backgroundColor: myColor,
  width: 30,
  height: 30
}));
Run Code Online (Sandbox Code Playgroud)

对于使用 typescript 的人,您还需要将 prop 类型添加到CreateStyledComponent

type DivProps = {
  myColor: string;
};

const Div = styled(Box)<DivProps>(({ theme, myColor }) => ({
  backgroundColor: myColor,
  width: 30,
  height: 30
}));
Run Code Online (Sandbox Code Playgroud)
<StyledBox myColor="pink" />
Run Code Online (Sandbox Code Playgroud)

如果您想在自定义组件中使用系统属性Box(如和 )Typography,您可以使用extendSxProp如下示例:

import { unstable_extendSxProp as extendSxProp } from "@mui/system";

const StyledDiv = styled("div")({});

function DivWithSystemProps(inProps) {
  const { sx } = extendSxProp(inProps);
  return <StyledDiv sx={sx} />;
}
Run Code Online (Sandbox Code Playgroud)
<DivWithSystemProps
  bgcolor="green"
  width={30}
  height={30}
  border="solid 1px red"
/>
Run Code Online (Sandbox Code Playgroud)

解释

  • styled("div")():将sx道具添加到您的自定义组件中
  • extendSxProp(props):收集顶级系统道具并将其放入属性中sx
const props = { notSystemProps: true, color: 'green', bgcolor: 'red' };
const finalProps = extendSxProp(props);

// finalProps = {
//   notSystemProps: true,
//   sx: { color: 'green', bgcolor: 'red' }
// }
Run Code Online (Sandbox Code Playgroud)

要与打字稿一起使用,您需要为所有系统属性添加类型:

type DivSystemProps = SystemProps<Theme> & {
  sx?: SxProps<Theme>;
};

function DivWithSystemProps(inProps: DivSystemProps) {
  const { sx, ...other } = extendSxProp(inProps);
  return <StyledDiv sx={sx} {...other} />;
}
Run Code Online (Sandbox Code Playgroud)

Codesandbox 演示


Muh*_*med 42

如何在 Material ui 中同时使用 props 和 theme 的解决方案:

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>
    );
}
Run Code Online (Sandbox Code Playgroud)

  • @SrinjoySantra 您确定在样式声明后添加了另一个 () 吗?const { div } = useStyles(props)(); (3认同)

Jam*_*Tan 33

这就是你想要的.

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;
Run Code Online (Sandbox Code Playgroud)

然后你就可以这样使用它:

<MyComponent color="yellow" backgroundColor="purple">
    Well done
</MyComponent>
Run Code Online (Sandbox Code Playgroud)

记得像下面那样创建一个类组件,或者在重新渲染时你会失去焦点.

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;
Run Code Online (Sandbox Code Playgroud)

  • 现在,我们如何在 TypeScript 中做到这一点...... (3认同)

Jöc*_*ker 33

这里的打字稿解决方案:

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>;
}
Run Code Online (Sandbox Code Playgroud)

如果你想玩它,试试这个 CodeSandbox


Ken*_*ory 10

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

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

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

这是我做的:

  1. 使用backgroundColorprop 渲染组件:
// in index.js
if (rootElement) {
  render(<Demo backgroundColor="#f00" />, rootElement);
}
Run Code Online (Sandbox Code Playgroud)
  1. 使用此prop可以为卡应用内联样式:
    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
Run Code Online (Sandbox Code Playgroud)

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

有关其他选项,请查看文档的" 替换"部分.


Dom*_*cum 10

现在可以使用@ 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>;
}
Run Code Online (Sandbox Code Playgroud)

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

这段代码改编自使用的demomakeStyles但是其他Material-UI API styledwithStyles示例)中也提供了此功能。

引进@材料的UI /风格关闭在接受的答案中提到的问题


Ode*_*Dov 9

该线程中缺少一个props用途withStyles(并导致认为它不受支持)

但这对我有用(例如样式 a MenuItem):

const StyledMenuItem = withStyles((theme) => ({
 root: {
  '&:focus': {
    backgroundColor: props => props.focusBackground,
    '& .MuiListItemIcon-root, & .MuiListItemText-primary': {
      color: props => props.focusColor,
    },
  },
 },
}))(MenuItem);
Run Code Online (Sandbox Code Playgroud)

然后像这样使用它:

 <StyledMenuItem focusColor={'red'} focusBackground={'green'}... >...</StyledMenuItem>
Run Code Online (Sandbox Code Playgroud)


MOS*_*OSI 9

@穆伊v5

您可以使用styled() 实用程序(确保导入正确的实用程序)和shouldForwardProp选项。在下面的示例中SomeProps传递给div组件

import { styled } from '@mui/material'

interface SomeProps {
  backgroundColor: 'red'|'blue',
  width: number
}
const CustomDiv  = styled('div', { shouldForwardProp: (prop) => prop !== 'someProps' })<{
  someProps: SomeProps;
}>(({ theme, someProps }) => {
  return ({
    backgroundColor: someProps.backgroundColor,
    width: `${someProps.width}em`,
    margin:theme.spacing(1)
  })
})
Run Code Online (Sandbox Code Playgroud)


Pin*_*Woo 7

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>;
}
Run Code Online (Sandbox Code Playgroud)