首页 > 解决方案 > 如何在本机反应中更改数组元素的样式

问题描述

我留下了一小段示例代码,因为我有我的代码,实际上我的代码我在 FlatList 中显示它......但在这里我在 .map 中给他留下了类似的东西,实际上是相同的东西,它们是动态视图,我希望在单击按钮后,视图会更改样式(Position Abosulte、Width、Backgorund 颜色等)

import { Text, View, StyleSheet, TouchableOpacity } from 'react-native';
import Constants from 'expo-constants';
import AssetExample from './components/AssetExample';

let shopping = ['bread', 'milk', 'cheese', 'hummus', 'noodles'];

export default function App() {
  return (
    <View style={styles.container}>
      {shopping.map((data, idx) => {
        return (
          <View
            style={{
              width: '100%',
              height: 70,
              backgroundColor: '#f7f7f7',
              marginTop: 5,
              marginBottom: 5,
              borderColor: '#dfdfdf',
              borderWidth: 1,
              alignItems: 'center',
            }}>
            <Text>Tex: {data}</Text>

//I press this buttom, i want change this View Styles!!!, only this view

            <TouchableOpacity onPress={() => {}}>
              <View
                style={{
                  width: '100%',
                  height: 30,
                  justifyContent: 'center',
                  alignItems: 'center',
                  backgroundColor: '#f7f7f7',
                  marginTop: 5,
                  marginBottom: 5,
                  borderColor: '#dfdfdf',
                  borderWidth: 1,
                  borderRadius: 15,
                }}>
                <Text style={{ width: '100%' }}>Change</Text>
              </View>
            </TouchableOpacity>
          </View>
        );
      })}
    </View>
  );
}

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

标签: react-native

解决方案


您可以拥有一个状态变量,然后将其设置为更改样式。

<TouchableOpacity onPress={() => this.setState({changeStyleIndex:index})}>
          <View
            style={this.state.changeStyleIndex != index{
              width: '100%',
              height: 30,
              justifyContent: 'center',
              alignItems: 'center',
              backgroundColor: '#f7f7f7',
              marginTop: 5,
              marginBottom: 5,
              borderColor: '#dfdfdf',
              borderWidth: 1,
              borderRadius: 15,
            }:{change style goes here}}>
            <Text style={{ width: '100%' }}>Change</Text>
          </View>
        </TouchableOpacity>

推荐阅读