javascript - how to change background of a touchableOpacity in iteration - Stack Overflow

I am looping an array , wrapping each item into touchableOpacity,attempting to change background Co

I am looping an array , wrapping each item into touchableOpacity , attempting to change background Color of the clicked item on onPress event, my issue is that its changing the background color of the whole items , is there a way to change background Color to only the clicked item , here is my code

 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'
            })
        }
    }

I am looping an array , wrapping each item into touchableOpacity , attempting to change background Color of the clicked item on onPress event, my issue is that its changing the background color of the whole items , is there a way to change background Color to only the clicked item , here is my code

 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'
            })
        }
    }
Share Improve this question edited Feb 22, 2019 at 16:48 dsaton22 asked Feb 22, 2019 at 16:40 dsaton22dsaton22 1071 gold badge1 silver badge7 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 3

Hey I have made this example and I hope this solves your problem.Find working example here.(https://snack.expo.io/@shrutigarg/touchableopacity-background-change-onclick)

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',
  },
});

Your code changes the color of all the items as it is unable to uniquely identify the item you clicked. The color you are changing is not associated with a particular item.

There are many ways to solve the problem. Here is one way where I create a separate ponent for each item, so each of these item's have their own state.

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"
  }
});

You need to reference to cat and index directly, for that you should send the Event.target it should work like this example: I'm dispatching an event onPress, you should have access to the event.target inside of the onPress handler function.

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)

    }

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1742340111a4425452.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信