【问题标题】:React js random color反应js随机颜色
【发布时间】:2020-11-15 10:39:53
【问题描述】:

我在我的组件https://ibb.co/PwLSMYH 中使用随机颜色,一切正常,每次刷新页面时,我的颜色都会改变,一切都很好,但我每个块都有相同的颜色,我希望每个块有不同的颜色(这是一个示例图片https://ibb.co/jbz50nt

import React from 'react';
import "./Achievements.css";

import crown from "./icons/online-course.png"
import goal from "./icons/goal.png"
import money from "./icons/money.png"
import target from "./icons/target.png"
import clipboard from "./icons/clipboard.png"
import climbing from "./icons/climbing.png"

export class AchievementsBeta extends React.Component {
    constructor() {
        super();
        this.state = {
            CoursesPage: [
                {
                    img: crown,
                    cardInfo: "Engaged in!",
                    cardLabel: "Complete the lesson",
                    cardColorStyle: 'card__fire',
                },

                {
                    img: goal,
                    cardInfo: "The first path to victory",
                    cardLabel: "complete five courses",
                    cardColorStyle: 'card__fire',
                },

                {
                    img: money,
                    cardInfo: "Piggy bank",
                    cardLabel: "Earn 100 XP",
                    cardColorStyle: 'card__fire',
                },

                {
                    img: target,
                    cardInfo: "Sniper",
                    cardLabel: "Complete the course without errors",
                    cardColorStyle: 'card__fire',
                },

                {
                    img: clipboard,
                    cardInfo: "Dear Citizen",
                    cardLabel: "Fill in all credentials",
                    cardColorStyle: 'card__fire',
                },

                {
                    img: climbing,
                    cardInfo: "My first avatar",
                    cardLabel: "Set avatar",
                    cardColorStyle: 'card__fire',
                },
            ],

            bgColor: [
                '#1ec891',
                '#ff725e',
                '#ffd05b',
            ],

            selectedColor: '',
        }
    }

    componentDidMount() {
        this._getRandomColor()
    }

    _getRandomColor(){
        const item = this.state.bgColor[Math.floor(Math.random()*this.state.bgColor.length)];
        this.setState({
            selectedColor: item,
        })
    }

    render() {

        const resultsRender = this.state.CoursesPage.map((user, index) => {
            return (

                <div style={{ width: "100%", marginBottom: "35px" }} key={index}>
                    <div style={{borderLeft: `5px solid ${this.state.selectedColor} `}} className={`${"Beta"} ${"card__fire"}`}>
                        <div className={"imgContainer"}>
                            <img src={user.img} alt="" />
                        </div>

                        <div>
                            <div className="cardInfo">
                                <p>{user.cardInfo}</p>
                            </div>

                            <div className="cardDescription">
                                <p>{user.cardLabel}</p>
                            </div>
                        </div>
                    </div>
                </div>

            );
        }

        );

        return (
            <div>
                {resultsRender}
            </div>
        );
    }
}

【问题讨论】:

    标签: javascript arrays reactjs random


    【解决方案1】:

    您必须移动在子组件内获取随机颜色的函数。

    目前,没有子组件,您只需在父组件安装时随机化一次,然后使用该随机颜色状态映射渲染卡片。

    所以,我的建议是创建一个子组件,当它被挂载并分离颜色状态时,它具有自己的随机颜色功能。

    然后,使用该子组件进行地图渲染并以自己的颜色状态显示您的卡片。

    TL:DR ;将 parent 的 selectedColor 单一状态移动到孩子自己的颜色状态。

    请参考我的代码框: https://codesandbox.io/s/color-randomizer-evogk?file=/src/ColorCard.js

    【讨论】:

      【解决方案2】:

      尝试更改您的 _getRandomColor 函数以获取随机颜色并且不要更改状态。该函数将是一个纯函数。

      然后可以在状态下CoursesPage数组的每个元素上添加一个blockColor键:

      this.state = {
        CoursesPage: [
          {
            img: crown,
            cardInfo: "Engaged in!",
            cardLabel: "Complete the lesson",
            cardColorStyle: 'card__fire',
            blockColor: this._getRandomColor(),
          },
          ...
        ],   
      }        
      

      并在渲染块时使用它:

      const resultsRender = this.state.CoursesPage.map((user, index) => {
        return (
          <div style={{ width: "100%", marginBottom: "35px" }} key={index}>
            <div
              style={{ borderLeft: `5px solid ${user.blockColor} ` }}
              className={`${"Beta"} ${"card__fire"}`}
            >
              <div className={"imgContainer"}>
                <img src={user.img} alt="" />
              </div>
      
              <div>
                <div className="cardInfo">
                  <p>{user.cardInfo}</p>
                </div>
      
                <div className="cardDescription">
                  <p>{user.cardLabel}</p>
                </div>
              </div>
            </div>
          </div>
        );
      });
      

      【讨论】:

        【解决方案3】:

        您可以在渲染render 方法中的每个项目之前更改CoursesPage,方法是在其上调用reduce 方法来更改每个对象的结构并为其附加随机颜色

        class App extends React.Component {
        
          constructor(props) {
            super(props);
            this.state = {
              CoursesPage: [
                {
                    img: "crown",
                    cardInfo: "Engaged in!",
                    cardLabel: "Complete the lesson",
                    cardColorStyle: 'card__fire',
                },
        
                {
                    img: "goal",
                    cardInfo: "The first path to victory",
                    cardLabel: "complete five courses",
                    cardColorStyle: 'card__fire',
                },
        
                {
                    img: "money",
                    cardInfo: "Piggy bank",
                    cardLabel: "Earn 100 XP",
                    cardColorStyle: 'card__fire',
                },
        
                {
                    img: "target",
                    cardInfo: "Sniper",
                    cardLabel: "Complete the course without errors",
                    cardColorStyle: 'card__fire',
                },
        
                {
                    img: "clipboard",
                    cardInfo: "Dear Citizen",
                    cardLabel: "Fill in all credentials",
                    cardColorStyle: 'card__fire',
                },
        
                {
                    img: "climbing",
                    cardInfo: "My first avatar",
                    cardLabel: "Set avatar",
                    cardColorStyle: 'card__fire',
                },
              ],
              bgColor: [
                '#1ec891',
                '#ff725e',
                '#ffd05b',
              ],
            }
          }
          render() {
            let courses = [...this.state.CoursesPage].map((course) => {
                return {
                  ...course,
                  bgColor: this.state.bgColor[Math.floor(Math.random() * this.state.bgColor.length)]
                }
            })
            return <ul>
              {courses.map((c, idx) => {
                return (<li key={idx} style={{ backgroundColor: `${c.bgColor}` }}>
                  {c.cardInfo} 
                </li>);
              })}
            </ul>
          }
        }
        
        ReactDOM.render(<App />, document.querySelector('#root'));
        <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
        <div id="root"></div>

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-10-18
          • 1970-01-01
          • 2012-11-13
          • 2022-10-04
          • 2021-03-15
          • 1970-01-01
          相关资源
          最近更新 更多