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

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

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

慕虎7371278 2023-03-18 17:52:08
我有一系列带有一些 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)        // }    }
查看完整描述

1 回答

?
qq_遁去的一_1

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

你在这里改变每张图片的状态



this.setState({

        arrowShown: !this.state.arrowShown,

        arrowHidden: !this.state.arrowHidden

    })


并显示具有相同状态值的每个图像。这就是为什么每次翻转一个图像时所有图像都会被翻转的原因。


你能做的就是保持这样的状态



       this.state = {  

           [index1] : { arrowShown : true , arrowHidden :false }  ,

           [index2] : { arrowShown : true , arrowHidden :false }  ,

       //and so on

       }


然后每当基于点击图像的索引时,您只更新该特定索引的状态,就像这样......



       this.setState({[indexOfTheClickedImage ] : { 

                arrowShown: !this.state.[indexOfTheClickedImage].arrowShown ,

                arrowHidden: !this.state.[indexOfTheClickedImage].arrowHidden

       }}


查看完整回答
反对 回复 2023-03-18
  • 1 回答
  • 0 关注
  • 74 浏览
慕课专栏
更多

添加回答

举报

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