【问题标题】:How to create colored squares board in React?如何在 React 中创建彩色方块板?
【发布时间】:2020-10-23 19:43:51
【问题描述】:

我想创建一个带有彩色方块的板。关键是我想要一个具有例如 4 种颜色的数组,并且我需要用该数组中的随机颜色填充每个正方形。

现在我生成 n 个随机颜色(colors.js 文件)

export const randomUpTo = (max) => {
  return Math.floor(Math.random() * max);
};

const randomColor = () => {
  const r = randomUpTo(255);
  const g = randomUpTo(255);
  const b = randomUpTo(255);
  return `rgb(${r}, ${g}, ${b})`;
};

export const generateColors = (n) => {
  return Array.from(new Array(n), randomColor);
};

...我在 Board.js 组件中显示 n 个不同的方格:

import React, { Component } from "react";

import { generateColors } from "../../utils/colors";
import "./Board.css";

class Board extends Component {
  state = {
    colors: generateColors(12)
  };
    
  render() {
    const { colors } = this.state;

    const squares = colors.map((color, index) => {
      return (
        <div key={index} className="square" style={{ background: color }}></div>
      );
    });

    return <div className="squares">{squares}</div>;
  }
}

export default Board;

但这是错误的,因为我创建了 n 个(在本例中为 12 个)正方形并用 n 个(在本例中为 12 个)颜色填充它们。我需要有一个颜色数组(例如颜色 = [黑色、白色、蓝色、绿色])并用这个数组中的随机颜色填充 n 个正方形(在本例中为 12 个)。

【问题讨论】:

    标签: javascript arrays reactjs


    【解决方案1】:

    colors 是一个由颜色组成的数组,而不是单一颜色。所以你必须得到特定的颜色,例如按索引

    const squares = colors.map((color, index) => {
       const color = colors[Math.floor(Math.random() * 4)];
                                 // or dynamically   * colors.length
       return (
           <div key={index} className="square" style={{ background: color }}></div>
       );
    });
    

    【讨论】:

    • 是的,但我有 12 种颜色,我通过这 12 种颜色进行映射,创建 12 个不同的正方形。我需要 12 个正方形,例如数组中的 4 种颜色
    猜你喜欢
    • 1970-01-01
    • 2020-01-13
    • 2014-11-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-12
    • 1970-01-01
    相关资源
    最近更新 更多