[英]How to create colored squares board in React?
I want to create a board with colored squares.我想创建一个带有彩色方块的板。 The point is that I want to have an array with for example 4 colors and I need to fill every square with random color from that array.关键是我想要一个包含 4 种颜色的数组,我需要用该数组中的随机颜色填充每个方块。
Right now I generate n random colors (colors.js file)现在我生成 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);
};
...and I display n different sqaures in Board.js component: ...我在 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;
but it's wrong because I create n (12 in this case) squares and fill them with n (12 in this case) colors.但这是错误的,因为我创建了 n 个(在本例中为 12)个方块并用 n 个(在本例中为 12 个)颜色填充它们。 I need to have an array of colors (for example colors = [black, white, blue, green]) and fill n squares (12 in this case) with random color from this array.我需要有一个颜色数组(例如,颜色 = [黑色、白色、蓝色、绿色])并用该数组中的随机颜色填充 n 个方块(在本例中为 12 个)。
The colors
is an array of colors, not a single color. colors
是一组颜色,而不是单一颜色。 So you would have to get the particular color eg by index .所以你必须得到特定的颜色,例如通过index 。
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>
);
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.