呈现数字数组的 React 组件的不同背景颜色

我要在 React 组件中生成不同的背景颜色,该组件返回一个从 1 到 100 的数字数组。


偶数以及奇数和质数应具有单独的颜色。


目前,我的随机组件在 App 组件中呈现。


我现在的问题是如何为偶数、奇数和质数生成这些颜色。


到目前为止我所做的在下面。


应用组件


import React from 'react'

import Numbers from './Numbers'

import './Style.css'


export default function App() {

    // const numbers = [1]


const numbers = [];

for(let i=0; i<=31; i++){

    numbers.push(i);

    if(i % 2 === 0){

        // numbers.style.backgroundColor = 'green' ; 

    }

   }

    return (

      <div className='container'>

        <div className="child">

          <h1>Numbers List</h1>

          <ul>

            <Numbers className="block" numbers={numbers} />

            {/* <Numbers/> */}

          </ul>

        </div>

        

      </div>

    )

}


数字组件


import React from 'react'


export default function Numbers({ numbers }) {

  const list = numbers.map((number) => 

  <div key={number} className="numbers"><li  className="list">{number}</li></div>

  )

  return list

}

样式表


body{

  display: flex;

  justify-content: center;

  align-items: center;

  height: 100vh;

  width: 100vw;

.container{

  display: flex;

  justify-content: center;

  align-items: center;

  height: 100vh;

  width: 100vw;

.numbers{

  background-color: pink;

  width: 100px;

  height: 100px;

  border-right: 1px solid gray;

  border-bottom: 1px solid aliceblue;

  display: inline-flex;

  justify-content: center;

  align-items: center;

}

li{

  text-align: center;

  padding-top: 15px;

  font-size: 1.2rem;

  padding-left: 15px;

}


慕无忌1623718
浏览 216回答 3
3回答

萧十郎

你可以这样做import React from 'react'export default function Numbers({ numbers }) {&nbsp; const isPrime = num => {&nbsp; for(let i = 2; i < num; i++)&nbsp; &nbsp; if(num % i === 0) return false;&nbsp; return num > 1;&nbsp; }&nbsp; const isOdd = (num)=> { return num % 2;}&nbsp;&nbsp; const getBackGroundColor = (num)=>{&nbsp; &nbsp; &nbsp; &nbsp;let color = 'red';&nbsp; &nbsp; &nbsp; &nbsp;if(isOdd (num)) color ='red' //even&nbsp; &nbsp; &nbsp; &nbsp;else color ='green' //odd&nbsp; &nbsp; &nbsp; &nbsp;if(isPrime(num)) color = 'orange' //prime&nbsp;&nbsp; &nbsp; return color ;&nbsp; }&nbsp; const list = numbers.map((number) =>&nbsp;&nbsp; <div key={number} style={{backgroundColor: getBackGroundColor(number) }} className="numbers"><li&nbsp; className="list">{number}</li></div>&nbsp; )&nbsp; return list}

慕工程0101907

以下 css 使奇数背景为灰色,偶数背景为银色,素数背景为粉红色:li:nth-child(2),li:nth-child(odd) {&nbsp; background: pink;}li:first-child,li:nth-child(3n+6),li:nth-child(5n+10),li:nth-child(7n+14){&nbsp; background: grey}li:nth-child(2n+4) {&nbsp; background: silver}

千巷猫影

这对我有用,我调用 random() 函数,它从数组中生成随机颜色。const random = () => {&nbsp; &nbsp; const backgroundColor = ["#134563", "#27ae60", "#3263F3", "#FFDC61"];&nbsp; &nbsp; const randomColors = backgroundColor[Math.floor(Math.random() * backgroundColor.length + 0)];&nbsp; &nbsp; return randomColors;&nbsp; }random();
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript