【问题标题】:React.js: Is there a way to apply a separate style to a component to be rendered in array.map?React.js:有没有办法将单独的样式应用于要在 array.map 中呈现的组件?
【发布时间】:2020-09-10 02:58:36
【问题描述】:

下面的demo使用array.map来渲染三个块。

demo(CodeSandBox)

颜色的名称在Colors.tsx中定义。

export default {
  foo: "#ff6347",
  bar: "#4682b4",
  baz: "#90ee90"
};

有没有办法使用您定义的颜色单独更改由 array.map 渲染的块的颜色?

我在 JS 中使用 Emotion 作为 CSS。


下面是完整的代码。

/** @jsx jsx */
import { jsx, css } from "@emotion/core";
import colors from "./Colors";

export default function App() {
  const colorName = ["foo", "bar", "baz"];
  const Block = colorName.map((item, index) => {
    const blockStyle = css`
    ${baseStyle}
    background-color: ${colors.foo}; // ${colors.item} did not work.
  `;
    return (
      <li key={index}>
        <span>{item}</span>
        <div css={blockStyle} />
      </li>
    );
  });

  return <ul>{Block}</ul>;
}

const baseStyle = css`
  width: 100px;
  height: 100px;
`;

【问题讨论】:

    标签: javascript css reactjs emotion


    【解决方案1】:

    tldr

    background-color: ${colors[item]};
    

    colors 是一个对象。 colorName =&gt; color

    要通过 colorName 访问颜色,您可以使用 colors[colorName]

    因此在您的代码中:

    background-color: ${colors[colorName]}
    

    或(因为您将 colorName 命名为 item

    background-color: ${colors[item]};
    

    【讨论】:

    • 我将类型赋予颜色,它工作得很好。非常感谢。
    猜你喜欢
    • 1970-01-01
    • 2020-12-06
    • 1970-01-01
    • 2019-09-22
    • 2017-08-22
    • 2023-03-15
    • 1970-01-01
    • 2017-06-29
    • 2023-04-06
    相关资源
    最近更新 更多