【问题标题】:In Material UI how can I dynamically pass down the color to my style?在 Material UI 中,如何动态地将颜色传递给我的样式?
【发布时间】:2021-04-19 18:08:06
【问题描述】:

React 和 Material UI 的新手我不知道如何正确地动态传递颜色,我从 JSON 文件中提取,并且在我的搜索、StackOverflow 或文档中找不到很好的参考。

研究

尝试

给定 JSON 文件:

[
  {
    "label": "Home",
    "href": "/",
    "colorHover": ""
  },
  {
    "label": "Monday",
    "href": "/mon",
    "colorHover": "#35c5bd"
  },
  {
    "label": "Tuesday",
    "href": "/tues",
    "colorHover": "#fa8b25"
  },
  {
    "label": "Wednesday",
    "href": "/wed",
    "colorHover": "#f26531"
  }
]

我将它带入我的组件并循环遍历它:

  const getDrawerChoices = () => {
    return headersData.map(({ label, href, colorHover }) => {
      const colorChange = colorHover === '' ? 'inherit' : colorHover

      return (
        <Link
          {...{
            component: RouterLink,
            to: href,
            color: 'inherit',
            style: { textDecoration: 'none' },
            key: label,
          }}
        >
          <MenuItem className={menuItem.hover(colorChange)}>{label}</MenuItem>
        </Link>
      )
    })
  }

材质 UI 样式:

const useStyles = makeStyles(colorChange => ({
  menuItem: {
    '&:hover': {
      backgroundColor: `${colorChange} !important`,
    },
  },
}))

但是我抛出了一个错误。如何将颜色值动态传递给 useStyles 或者我是否需要内联?

【问题讨论】:

    标签: reactjs material-ui


    【解决方案1】:

    您必须创建一个自定义的makeStyle,将 prop 传递给每个键,如下所示:

    const useStyles = makeStyles({
      root: (props) => ({
        "&:hover": {
          backgroundColor: props.hoverColor
        }
      })
    });
    

    我会留下 sandbox link 和我测试过的 link 给文档。有什么可以告诉我的。

    【讨论】:

    • 是的,由于某种原因,我仍然收到错误消息:codesandbox.io/s/serene-shannon-52p3l?file=/src/components/…
    • 对,你不能在回调中使用钩子。我已经在link 上更新了解决方案,我的建议是拆分组件以便能够使用钩子并获取每个组件的自定义样式。
    • 啊我现在明白了。该领域的文档不是很清楚。
    猜你喜欢
    • 1970-01-01
    • 2020-02-15
    • 1970-01-01
    • 2023-02-23
    • 2018-01-04
    • 2021-02-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多