【问题标题】:Styling a React Material UI Component with a .map function使用 .map 函数为 React Material UI 组件设置样式
【发布时间】:2020-05-11 10:41:19
【问题描述】:

所以我有一组 Material UI 组件(对于我的精简版,我使用了两个简单的 Button 组件)。

当我在地图函数中迭代这些组件时,如何为这些组件添加样式?

例如,如何将图标的大小调整为 64px x 64px ?

import React from "react";
import "./styles.css";
import Button from "@material-ui/core/Button";
import SaveIcon from "@material-ui/icons/Save";
import DeleteIcon from "@material-ui/icons/Delete";
export default function App() {
  const buttons = [
    <Button
      variant="contained"
      color="primary"
      size="large"
      startIcon={<SaveIcon />}
    >
      Save
    </Button>,
    <Button
      variant="contained"
      color="secondary"
      size="large"
      startIcon={<DeleteIcon />}
    >
      Delete
    </Button>
  ];

  return (
    <div className="App">
      {buttons.map(currButton => {
        //How do I add style to each of these components as I iterate through them ?
        return currButton;
      })}
    </div>
  );
}

【问题讨论】:

    标签: javascript css reactjs material-ui jss


    【解决方案1】:

    您需要遍历以props 作为参数的函数数组,并返回Button 组件以及您传递的任何额外props

    export default function App() {
      const buttons = [
        props => (
          <Button
            variant="contained"
            color="primary"
            size="large"
            startIcon={<SaveIcon />}
            {...props}
          >
            Save
          </Button>
        ),
        props => (
          <Button
            variant="contained"
            color="secondary"
            size="large"
            startIcon={<DeleteIcon />}
            {...props}
          >
            Delete
          </Button>
        )
      ];
    
      return (
        <div className="App">
          {buttons.map(createButton => {
            const CustomButton = createButton({
              style: { backgroundColor: "red" }
            });
            return CustomButton;
          })}
        </div>
      );
    }
    

    【讨论】:

    • 这种方法在 CodeSandbox 中运行良好。但是,在我的开发模式下运行它时出现类型错误。 (注意:我使用 Flow 进行类型检查) - 我收到以下错误:TypeError: createButton is not a function。知道为什么吗?
    • @SimonLong 您确定您在CodeSandbox 中的内容与您在本地环境中的内容完全相同吗? console.log(typeof createButton) 显示什么?类型检查不应该影响任何事情。
    • 完全一样的代码。甚至将你的粘贴到。console.log(typeof createButton) 正在给 Object
    • @SimonLong 你也可以显示leftButtons 数组吗?看起来currButtonButton 类型的对象,而不是函数。
    • @SimonLong 很高兴你能弄清楚
    猜你喜欢
    • 2022-08-10
    • 2021-06-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-28
    • 2019-10-26
    • 2020-05-23
    • 2018-07-30
    相关资源
    最近更新 更多