Javascript 如何在迭代中更改touchableOpacity的背景

Javascript 如何在迭代中更改touchableOpacity的背景,javascript,react-native,Javascript,React Native,我正在循环一个数组,将每个项目包装成touchableOpacity,试图在onPress事件中更改单击项目的背景色, 我的问题是,它改变了整个项目的背景色,有没有办法改变背景色,只有点击的项目,这是我的代码 return this.props.categes.map( ( cat,i)=> <TouchableOpacity onPress = {() => this.changeBackground(i)} key =

我正在循环一个数组,将每个项目包装成touchableOpacity,试图在onPress事件中更改单击项目的背景色, 我的问题是,它改变了整个项目的背景色,有没有办法改变背景色,只有点击的项目,这是我的代码

 return this.props.categes.map( (

            cat,i)=>

            <TouchableOpacity onPress = {() => this.changeBackground(i)} key = {i} style={{alignSelf : 'center', paddingLeft: 5, paddingRight : 7, paddingTop : 5, paddingBottom : 5, backgroundColor : this.state.background}}>
            <Text style={{color : '#838D8D'}}> {cat.name}</Text>
            </TouchableOpacity>

            )

  changeBackground(item){

        if(item)
        {
            this.setState({
                background: 'red'
            })
        }
    }
返回这个.props.categes.map((
猫,我)=>
this.changeBackground(i)}key={i}style={{{{alignSelf:'center',paddingLeft:5,paddingRight:7,paddingTop:5,paddingBottom:5,backgroundColor:this.state.background}>
{cat.name}
)
更改背景(项目){
如果(项目)
{
这是我的国家({
背景:“红色”
})
}
}

您需要直接引用
cat
索引,为此您应该发送
事件。target
的工作原理如下: 我正在按
发送一个事件,您应该可以访问 onPress处理程序函数内部的
event.target

return this.props.categes.map( (

            cat,i)=>

            <TouchableOpacity onPress = {event => this.changeBackground(i)} key = {i} style={{alignSelf : 'center', paddingLeft: 5, paddingRight : 7, paddingTop : 5, paddingBottom : 5, backgroundColor : this.state.background}}>
            <Text style={{color : '#838D8D'}}> {cat.name}</Text>
            </TouchableOpacity>

            )

  changeBackground(event){

     //Here you should be able to check the touched object:

     console.log('Here is the touched cat: ', event.target)

    }
返回这个.props.categes.map((
猫,我)=>
this.changeBackground(i)}key={i}style={{{{alignSelf:'center',paddingLeft:5,paddingRight:7,paddingTop:5,paddingBottom:5,backgroundColor:this.state.background}>
{cat.name}
)
更改背景(事件){
//在这里,您应该能够检查触摸的对象:
console.log('这是触摸的猫:',event.target)
}

您的代码会更改所有项目的颜色,因为它无法唯一标识您单击的项目。您正在更改的颜色与特定项目不关联

有很多方法可以解决这个问题。这里有一种方法,我为每个项目创建一个单独的组件,这样每个项目都有自己的状态

import React, { Component } from "react";
import { StyleSheet, TouchableOpacity, View, Text } from "react-native";

export default class App extends React.Component {
  render() {
    let listOfItems = [1, 2, 3, 4, 5, 6, 7, 8, 9];

    return (
      <View style={styles.container}>
        {listOfItems.map(e => {
          return <ToggleButton key={e + "i"} />;
        })}
      </View>
    );
  }
}

class ToggleButton extends Component {
  state = {
    on: false
  };

  render() {
    const { on } = this.state;

    return (
      <TouchableOpacity
        onPress={() => this.setState({ on: !this.state.on })}
        style={{ height: 50, width: 50, backgroundColor: on ? "green" : "red" }}
      >
        <Text>ITEM</Text>
      </TouchableOpacity>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: "#fff",
    alignItems: "center",
    justifyContent: "center"
  }
});

import React,{Component}来自“React”;
从“react native”导入{样式表、TouchableOpacity、视图、文本};
导出默认类App扩展React.Component{
render(){
让listOfItems=[1,2,3,4,5,6,7,8,9];
返回(
{listOfItems.map(e=>{
返回;
})}
);
}
}
类ToggleButton扩展组件{
状态={
关于:错
};
render(){
const{on}=this.state;
返回(
this.setState({on:!this.state.on})
样式={{高度:50,宽度:50,背景颜色:开?“绿色”:“红色”}
>
项目
);
}
}
const styles=StyleSheet.create({
容器:{
弹性:1,
背景颜色:“fff”,
对齐项目:“中心”,
为内容辩护:“中心”
}
});

嘿,我已经做了这个例子,我希望这能解决你的问题。在这里找到工作的例子。()

import*as React from'React';
从“react native”导入{文本、视图、样式表、TouchableOpacity};
导出默认类App扩展React.Component{
建造师(道具){
超级(道具);
此.state={
类别:[
{cat_id:'1',cat_name:'abc',backgroundcolor:'ED2525'},
{cat_id:'2',cat_name:'xyz',backgroundcolor:'#ED2525'},
{cat_id:'3',cat_名称:'pqr',背景色:'#ED2525'},
{猫id:'4',猫名:'uvw',背景色:'#ED2525'},
{cat_id:'5',cat_name:'hij',backgroundcolor:'ED2525'},
],
改变:错,
};
}
changeBackground=项目=>{
让categes=JSON.parse(JSON.stringify(this.state.categes));
for(设x=0;x(
此.changeBackground(项目)}>
{' '}
{item.cat_name.toUpperCase()}
))}
);
}
}
const styles=StyleSheet.create({
容器:{
弹性:1,
为内容辩护:“中心”,
背景颜色:“#ecf0f1”,
填充:8,
对齐项目:“居中”,
},
});

谢谢Natasha,所以调用此.changeBackground我也应该传递事件?我认为仍然缺少一些东西,因为我正在更改组件的状态。组件内部的任何适当性都会调用该状态,它将受到影响。我不确定您的意思。你能提供一点背景或重构你的问题吗?谢谢
import * as React from 'react';
import { Text, View, StyleSheet, TouchableOpacity } from 'react-native';

export default class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      categes: [
        { cat_id: '1', cat_name: 'abc', backgroundcolor: '#ED2525' },
        { cat_id: '2', cat_name: 'xyz', backgroundcolor: '#ED2525' },
        { cat_id: '3', cat_name: 'pqr', backgroundcolor: '#ED2525' },
        { cat_id: '4', cat_name: 'uvw', backgroundcolor: '#ED2525' },
        { cat_id: '5', cat_name: 'hij', backgroundcolor: '#ED2525' },
      ],
      change: false,
    };
  }

  changeBackground = item => {
    let categes = JSON.parse(JSON.stringify(this.state.categes));

    for (let x = 0; x < this.state.categes.length; x++) {
      if (this.state.categes[x].cat_id == item.cat_id) {
        categes[x].backgroundcolor = '#0000FF';

        this.setState({
          categes: categes,
        });
      } else {
        categes[x].backgroundcolor = '#ED2525';

        this.setState({
          categes: categes,
        });
      }
    }
  };
  render() {
    return (
      <View style={styles.container}>
        {this.state.categes.map((item, key) => (
          <TouchableOpacity
            style={{
              width: 200,
              height: 60,
              alignItems: 'center',
              justifyContent: 'center',
              margin: 10,
              backgroundColor: item.backgroundcolor,
            }}
            onPress={() => this.changeBackground(item)}>
            <Text style={{ color: '#FFFFFF' }}>
              {' '}
              {item.cat_name.toUpperCase()}
            </Text>
          </TouchableOpacity>
        ))}
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    backgroundColor: '#ecf0f1',
    padding: 8,
    alignItems: 'center',
  },
});