为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

慕无忌1623718 2023-05-19 16:00:55
我要在 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;}
查看完整描述

3 回答

?
萧十郎

TA贡献1815条经验 获得超12个赞

你可以这样做


import React from 'react'


export default function Numbers({ numbers }) {

  const isPrime = num => {

  for(let i = 2; i < num; i++)

    if(num % i === 0) return false;

  return num > 1;

  }

  const isOdd = (num)=> { return num % 2;} 

  const getBackGroundColor = (num)=>{

       let color = 'red';

       if(isOdd (num)) color ='red' //even

       else color ='green' //odd

       if(isPrime(num)) color = 'orange' //prime 

    return color ;

  }


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

  <div key={number} style={{backgroundColor: getBackGroundColor(number) }} className="numbers"><li  className="list">{number}</li></div>

  )

  return list

}


查看完整回答
反对 回复 2023-05-19
?
慕工程0101907

TA贡献1887条经验 获得超5个赞

以下 css 使奇数背景为灰色,偶数背景为银色,素数背景为粉红色:


li:nth-child(2),

li:nth-child(odd) {

  background: pink;

}


li:first-child,

li:nth-child(3n+6),

li:nth-child(5n+10),

li:nth-child(7n+14)

{

  background: grey

}


li:nth-child(2n+4) {

  background: silver

}


查看完整回答
反对 回复 2023-05-19
?
千巷猫影

TA贡献1829条经验 获得超7个赞

这对我有用,我调用 random() 函数,它从数组中生成随机颜色。


const random = () => {

    const backgroundColor = ["#134563", "#27ae60", "#3263F3", "#FFDC61"];

    const randomColors = backgroundColor[Math.floor(Math.random() * backgroundColor.length + 0)];

    return randomColors;

  }

random();


查看完整回答
反对 回复 2023-05-19
  • 3 回答
  • 0 关注
  • 150 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信