根据数组索引更改图像状态 - React.js

我有一系列带有一些 svg 的卡片,需要根据点击单独(上下)更改状态。模态由引导程序处理。所以,我试图根据数组的索引更改 svg(硬编码)的状态。但是,即使我得到了 id(动态的),每次我点击 svg 箭头时,所有的 svg 都会改变状态。


我认为状态不应该在 for 循环中改变,我想知道问题是否来自 {this.state.arrowShown && }。因此,如何只改变被点击的卡片的svg状态,而不改变其他卡片的状态呢?


import Container from 'react-bootstrap/Container'

import Card from 'react-bootstrap/Card'

import Row from 'react-bootstrap/Row'

import Col from 'react-bootstrap/Col'

import { withTranslation } from 'react-i18next';

import Accordion from 'react-bootstrap/Accordion'

import Button from 'react-bootstrap/Button'


class ProjectCard extends React.Component {


    constructor() {

        super();

        this.state = {

            arrowShown: true,

            arrowHidden: false,

        }

        this.handleClick = this.handleClick.bind(this);

    }


    handleClick(event, index) {

        const id = event.currentTarget.id;

        const projectArr = this.props.projects;

        console.log("this.props.porjects", this.props.projects)

        for (var i = 0; i < projectArr.length; i++) {

            console.log("projectArr[i].idP1", projectArr[i].idP2)

            if (projectArr[i].idP2 === id) {

                console.log("same same")

                this.setState({

                    arrowShown: !this.state.arrowShown,

                    arrowHidden: !this.state.arrowHidden

                })

                // newState[projectArr[i].idP2.arrowShown] = projectArr[i].idP2 === projectArr[i].idP2

            }

        }

        //     // this.setState(newState)

        // }

    }





慕虎7371278
浏览 80回答 1
1回答

qq_遁去的一_1

你在这里改变每张图片的状态this.setState({&nbsp; &nbsp; &nbsp; &nbsp; arrowShown: !this.state.arrowShown,&nbsp; &nbsp; &nbsp; &nbsp; arrowHidden: !this.state.arrowHidden&nbsp; &nbsp; })并显示具有相同状态值的每个图像。这就是为什么每次翻转一个图像时所有图像都会被翻转的原因。你能做的就是保持这样的状态&nbsp; &nbsp; &nbsp; &nbsp;this.state = {&nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;[index1] : { arrowShown : true , arrowHidden :false }&nbsp; ,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;[index2] : { arrowShown : true , arrowHidden :false }&nbsp; ,&nbsp; &nbsp; &nbsp; &nbsp;//and so on&nbsp; &nbsp; &nbsp; &nbsp;}然后每当基于点击图像的索引时,您只更新该特定索引的状态,就像这样......&nbsp; &nbsp; &nbsp; &nbsp;this.setState({[indexOfTheClickedImage ] : {&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; arrowShown: !this.state.[indexOfTheClickedImage].arrowShown ,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; arrowHidden: !this.state.[indexOfTheClickedImage].arrowHidden&nbsp; &nbsp; &nbsp; &nbsp;}}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript