map里的点击事件,会影响其他map出来的元素

我在map里传了一个onQRScreening方法,点击切换打开/关闭,但是点击一个,所有map出来的元素都会受影响,这该怎么解决

https://img1.mukewang.com/5c68fc13000149ba02510132.jpg

https://img.mukewang.com/5c68fc160001be9802210133.jpg

https://img2.mukewang.com/5c68fc240001e71d07010899.jpg

红颜莎娜
浏览 605回答 1
1回答

喵喵时光机

因为你所有item的状态都是用QRScreening来判断的,解决方法:在onQRScreening传入index,将点击的index存入QRScreening中,通过判断QRScreening中是否存在当前点击对象的index来改变开关的状态。大致代码如下(我用的react版本是15.4.2):&nbsp; &nbsp; state = { QRScreening: [] }&nbsp; &nbsp; onQRScreening = (index) => {&nbsp; &nbsp; &nbsp; &nbsp; let QRScreening = this.state.QRScreening&nbsp; &nbsp; &nbsp; &nbsp; // 判断是否点击过,点击过则删除,未点击过则添加&nbsp; &nbsp; &nbsp; &nbsp; QRScreening.indexOf(index) === -1 ? QRScreening.push(index) : QRScreening.splice(QRScreening.indexOf(index), 1)&nbsp; &nbsp; &nbsp; &nbsp; this.setState({&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; QRScreening&nbsp; &nbsp; &nbsp; &nbsp; })&nbsp; &nbsp; }&nbsp; &nbsp; render() {&nbsp; &nbsp; &nbsp; &nbsp; return (&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <div>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {[1, 2, 3].map((m, index) => {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; let flag = this.state.QRScreening.indexOf(index) === -1&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return (&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <div key={index} onClick={() => this.onQRScreening(index)}>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {flag ? '关闭' : '开启'}&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; </div>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; )&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; })}&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; </div>&nbsp; &nbsp; &nbsp; &nbsp; )&nbsp; &nbsp; }
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript