【问题标题】:How to pass props to to material-ui styles in a sub-selector如何在子选择器中将道具传递给 Material-ui 样式
【发布时间】:2020-02-15 21:51:48
【问题描述】:

如果被问及回答,通常会道歉......

我有一个样式表:

const styles = createStyles({
    root: {background: 'blue', color: 'red'},
    highlightedWrapper: {
        '& $root': {
           background: 'green',
           color: 'black'
        }
    }
})

...我这样调用:

const useStyles = makeStyles(kanbanStyles);

...然后像这样在我的组件中引用:

const classes = useStyles()

到目前为止,一切都很好。我想做的是将道具传递给useStyles(),然后我会在样式表中引用它。所以这行得通:

const classes = useStyles({color: 'yellow'})

const styles = createStyles({
    root: (props) => { return {background: 'blue', color: props.color}},
    highlightedWrapper: {
        '& $root': {
           background: 'green',
           color: 'black'
        }
    }
})

...但我不知道如何调用子选择器内的函数。就像,这对我不起作用:

const styles = createStyles({
    root: {background: 'blue', color: props.color},
    highlightedWrapper: {
        '& $root': {
           background: 'green',
           color: (props) => props.color
        }
    }
})

我已经尝试了上述语法的各种排列,将其放在hightlightedWrapper: 之后和'& $root': 之后,但没有任何效果。

帮助?

谢谢!!

【问题讨论】:

  • root 中使用与highlightedWrapper (color: (props) => props.color) 中相同的语法,应该没问题。
  • @RyanCogswell 除非我遗漏了某些东西(很可能是这种情况),否则我已经尝试过这种语法。请参阅我上面的示例。正如我在下面提到的,我使用的是 Typescript,这意味着我必须使用 createStyles,我想知道这是否会以某种方式把事情搞砸?
  • 请提供code sandbox 重现您的问题。
  • 是的……是的,好主意。给我一点。

标签: reactjs material-ui jss


【解决方案1】:

向@RyanCogswell 提供答案以获得答案,但问题是,如果您要使用函数作为样式,为了处理动态道具,您必须在任何地方都使用函数样式被引用。所以这会中断:

  wrapper: {
    '& $name': {
      color: (props) => (props.color ? props.color : 'blue')
    }
  },
  name: {
    color: 'green'
  }

...但这会起作用:

  wrapper: {
    '& $name': {
      color: (props) => (props.color ? props.color : 'blue')
    }
  },
  name: {
    color: (props) => 'green'
  }

注意(props) => 'green'

这是一个可能不会很快得到解决的错误: https://github.com/mui-org/material-ui/issues/13672#issuecomment-541118923

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-24
    • 2021-09-11
    • 2020-08-12
    • 2020-05-08
    • 1970-01-01
    • 2020-03-09
    相关资源
    最近更新 更多