乡亲。我可能有一个新手问题,不过我还是会射击。下面的代码段非常简单,我不应该遇到问题,但是我们开始吧。我正在尝试获取ColorsGrid组件中的颜色列表。简而言之,当用户通过下拉列表更改难度级别时,应生成一组新的颜色并进行显示。我认为这是一个非常简单的练习,但是事情并没有按预期进行。每当我改变难度时,它都不会做出反应(渲染ColorsGrid组件),只有在我再次选择另一个(难度)级别之后,上一个级别才会引发重新渲染。例如,如果我要在初始渲染后选择“中”(默认级别设置为“简单”),则没有任何变化。但是,如果我回到“轻松”(或选择其他任何难度),那么是否会发生与前一个(中等难度)相对应的更改,即ColorsGrid重新渲染,因此显示了与中等难度相对应的网格。我究竟做错了什么?
以下是相关代码。
import React, { Component } from 'react';
import ReactDOM from 'react-dom';
// Get random rgb color
function randomColor() {
let r = Math.floor(Math.random() * 256);
let g = Math.floor(Math.random() * 256);
let b = Math.floor(Math.random() * 256);
return `rgb(${r}, ${g}, ${b})`;
}
// Set length of color list array as a funciton of difficulty
function colorsListLength(difficulty) {
switch (true) {
case difficulty === 'expert':
return 25;
case difficulty === 'hard':
return 20;
case difficulty === 'medium':
return 10;
default:
return 5;
}
}
// Get color list array
function colorsList(colorsLength = 5) {
const colors = [];
while (colors.length < colorsLength) {
colors.push(randomColor());
}
return colors;
}
// Set random color to guess from (above) color list array
function randomColorToGuess(colors) {
const index = Math.floor(Math.random() * colors.length);
return colors[index];
}
// Set number of game tries as a function of difficulty
function numberOfTries(difficulty) {
switch (true) {
case difficulty === 'expert' || difficulty == 'hard':
return 2;
case difficulty === 'medium':
return 1;
default:
return 0;
}
}
慕容3067478
繁星淼淼
相关分类