首页 > 解决方案 > 如何在 React 映射组件上进行独立样式更改

问题描述

当我尝试更改映射的 TouchableOpacity 的样式时遇到问题。

我映射了一个 TouchableOpacity 列表,我希望当我单击一个时,backgroundColor 仅在我单击的那个上更改(黑色),但也重置我之前单击的另一个 TouchableOpacity 的 backgroundColor。

因此,例如,如果我单击第一个 TouchableOpacity,则该背景变为黑色。之后,如果我点击第二个,第二个的背景变成黑色,但第一个的背景又变成灰色。

export default class Playground extends Component {
      state = {
            isPressed: false
      };

      handlePress = () => {
            this.setState({
                  isPressed: !this.state.isPressed
            });
      };

      render() {
            let array = [0, 1, 2];
            return (
                  <View style={styles.container}>
                        <Text>Test</Text>
                        {array.map(item => {
                              return (
                                    <TouchableOpacity
                                          key={item}
                                          style={this.state.isPressed ? styles.buttonPressed : styles.button}
                                          onPress={this.handlePress}
                                    >
                                          <Text>Click on it</Text>
                                    </TouchableOpacity>
                              );
                        })}
                  </View>
            );
      }
}

const styles = StyleSheet.create({
      container: {
            flex: 1,
            backgroundColor: '#fff',
            alignItems: 'center',
            justifyContent: 'center',
            marginTop: 50
      },
      button: {
            backgroundColor: 'grey'
      },
      buttonPressed: {
            backgroundColor: 'black'
      }
});

这是我尝试过的,但是当我单击一个 TouchableOpacity 时,它们的背景颜色都会改变。

我想只定位一个并同时重置另一个

标签: reactjsreact-nativereact-component

解决方案



it's good working

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


export default class Playground extends Component {
  state = {
    isPressed: false
  };

  handlePress = () => {
    this.setState({
      isPressed: !this.state.isPressed
    });
  };

  render() {
    let array = \[0, 1, 2\];
    return (
      <View style={styles.container}>
        <Text>Test</Text>
        {array.map(item => {
          return (
            <TouchableOpacity
              key={item}
              style={this.state.isPressed === false ? styles.buttonPressed : styles.button}
              onPress={this.handlePress}
            >
              <Text>Click on it</Text>
            </TouchableOpacity>
          );
        })}
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'center',
    marginTop: 50
  },
  button: {
    backgroundColor: 'grey'
  },
  buttonPressed: {
    backgroundColor: 'black'
  }
});

在此处输入图像描述


推荐阅读