首页 > 解决方案 > 在 React 中从数组中渲染特定元素

问题描述

我的目标是有一个框,可以在数组中按顺序呈现颜色的单词。

我正在为渲染数组的每个元素的概念而苦苦挣扎。我假设您需要挑选每个元素,将其存储在一个变量中,然后渲染该变量,但每次我尝试它时都会遇到死胡同。

您将在下面的代码中看到我注释掉的尝试。我也尝试过forEach,但 React 在尝试使用forEach.

此外,我被告知避免使用.mapand afor loop如果可能的话。

import React from 'react'

class ColorSwitch extends React.Component {
    constructor(props) {
        super(props)
            this.state = {
                colors: ["white", "orange", "purple", "black", "green"]
            }
    }

    nextColor = () => {
        let newColor = this.state.colors

        // let setColor = newColor[0] += 1 (DIDNT WORK)

        this.setState({colors: setColor})
    }

    render() {
        let { colors } = this.state
        return(
            <div className="box" onClick={this.nextColor}>
            <p>{this.setColor}</p>
            </div>
        )
    }
}

export default ColorSwitch

在此先感谢您的帮助。

标签: javascriptarraysreactjs

解决方案


从道具中获取颜色(如果它是静态的,则使用 const),并将其存储在currentColorIndex内部状态。

调用时按 1nextColor递增currentColorIndex(我使用 % colors.length 进行下一个循环)。要渲染抓取颜色currentColorIndex

const colors = ["white", "orange", "purple", "black", "green"]

class ColorSwitch extends React.Component {
    state = {
      currentColorIndex: 0
    }

    nextColor = () =>
      this.setState(({ currentColorIndex }) => ({
        currentColorIndex: (currentColorIndex + 1) % this.props.colors.length
      }))

    render() {
        const { currentColorIndex } = this.state
        const { colors } = this.props
        
        const color = colors[currentColorIndex];
        
        return(
            <div className="box" 
            onClick={this.nextColor} 
            style={{ background: color }}>
              <p>{color}</p>
            </div>
        )
    }
}

ReactDOM.render(
  <ColorSwitch colors={colors} />,
  demo
)
<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="demo"></div>


推荐阅读