简体   繁体   中英

React.js: Is there a way to apply a separate style to a component to be rendered in array.map?

The following demo uses array.map to render three blocks.

demo(CodeSandBox)

The names of the colors are defined in Colors.tsx .

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

Is there a way to change the color of a block rendered by array.map individually using the color you defined?

I use Emotion for CSS in JS.


Below is the entire code.

/** @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;
`;

tldr

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

colors is an object. colorName => color

To access a color by colorName you can use colors[colorName]

Thus in your code:

background-color: ${colors[colorName]}

or (since you named the colorName item )

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM