【问题标题】:How can I dynamically set style of a mapped element without using inline styling?如何在不使用内联样式的情况下动态设置映射元素的样式?
【发布时间】:2020-11-08 10:30:00
【问题描述】:

我正在编写一个带有包含对象数组的父组件的 React 函数:

let const ingredients = [
    {name:"lettuce",color:"green"},
    {name:"tomato",color:"red"}
]

...

在子组件中,有一个 map 函数可以将数组分解为单个项目以显示在 div 中。

将对象className:"name" 的CSS 样式定义为设置backgroundColor: {ingredient.color}; 的最佳做法是什么?我试图避免手动输入“成分”的整个键/值集,以允许在不破坏代码的情况下更新对象。

我目前正在使用内联样式,有人建议我不要这样做。目前使用:

let burg = props.toppings.map((item) => {
const divColor = {backgroundColor: item.color};
return (<div style={divColor}>{item.name}</div>)

【问题讨论】:

  • 有什么特别的原因不想使用内联样式吗?
  • 我的助教(他的简历很不错)通常建议不要使用内联样式。

标签: css reactjs jsx


【解决方案1】:

当你有其他解决方案来做你想做的事情时,内联样式是不好的。在这里,您有一个颜色字符串(红色、绿色等),因此您可以为每种颜色编写一个 css 类,但这当然是一个非常糟糕的主意。内联样式是这样做的好方法。

【讨论】:

    【解决方案2】:

    我建议设置 div 的类而不是样式。这样你就可以改变外观而不需要内联样式。

    您可以为生菜创建一个背景颜色为绿色的 css 类,而不是使用您设置的 item.color class={ item.name }

    【讨论】:

    • 因此,如果有数百个项目,您将不得不创建数百个类。坏主意
    • 这是一个公平的观点。重新阅读问题,并且考虑到项目之间只有颜色不同,内联样式可能是最好的解决方案。如果有更多的差异要被设计,我可能仍然会选择类,特别是如果它们可以分类的话。
    【解决方案3】:

    你可以这样用。

    如果你使用scss,css会更方便

    // css
    .color-green {
      color: green;
    }
    .color-red {
      color: red;
    }
    
    import React from "react";
    import "./styles.css";
    
    const ingredients = [
      { name: "lettuce", color: "green" },
      { name: "tomato", color: "red" }
    ];
    const Vegetable = ({ color, text }) => {
      return (
        <p>
          this is <span className={`color-${color}`}>{text}</span> color{" "}
        </p>
      );
    };
    
    export default function App() {
      return (
        <div className="App">
          <h1>Hello CodeSandbox</h1>
          <h2>Start editing to see some magic happen!</h2>
          {ingredients.map((item, index) => {
            return <Vegetable key={index} color={item.color} text={item.name} />;
          })}
        </div>
      );
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-11-08
      • 2018-05-05
      • 2013-12-29
      • 1970-01-01
      • 2021-01-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多