首页 > 解决方案 > 单独反应原生 onPress TouchableHighlights?

问题描述

我只是想创建一个简单的井字游戏。为此,我需要 9 个按钮。我使用被 TouchableHighlights 包围的视图创建了一个基本布局,以使它们可点击。

如果我点击按钮,只有那个按钮应该改变它的颜色,但目前所有按钮都同时改变颜色。有人知道如何解决这个问题吗?

我不知道如何为每个 TouchableHighlight 单独处理状态。

非常感谢所有帮助。

import React, {Component} from 'react';
import {
  AppRegistry,
  StyleSheet,
  Text,
  View,
    Dimensions,
  TouchableHighlight
} from 'react-native';

var screenWidth = Dimensions.get('window').width;
screenWidth-=36;
var screenHeigth = Dimensions.get('window').height;

let randomHex = () => {
  let letters = '0123456789ABCDEF';
  let color = '#';
  for (let i = 0; i < 6; i++ ) {
    color += letters[Math.floor(Math.random() * 16)];
  }
  return color;
}

export default class randomBackground extends Component {
  constructor(props) {
    super(props)

    this.state = {
      backgroundColor: '#f5aef5'
    };
  }

  render() {
    return (
        <View style={{backgroundColor: '#f5f5f5', flex: 1}}>

          <Text style={{color:'black', alignSelf: 'center', fontSize: 100, marginTop: 60}}>TicTacToe</Text>

          <View style={styles.outercardview}>

            {/* row 1 */}
            <View style={{flexDirection:'row'}}>

              <TouchableHighlight onPress={() => this.setState({backgroundColor: randomHex()})}  underlayColor="white" style={{ height: screenWidth/3, width: screenWidth/3, borderRadius: 9, margin: 3, backgroundColor: this.state.backgroundColor}}>
                <View>

                </View>
              </TouchableHighlight>

              <TouchableHighlight onPress={() =>this.setState({backgroundColor: randomHex()})} underlayColor="white" style={{ height: screenWidth/3, width: screenWidth/3, borderRadius: 9, margin: 3, backgroundColor: this.state.backgroundColor}}>
                <View>

                </View>
              </TouchableHighlight>

              <TouchableHighlight onPress={() => this.setState({backgroundColor: randomHex()})} underlayColor="white" style={{ height: screenWidth/3, width: screenWidth/3, borderRadius: 9, margin: 3, backgroundColor: this.state.backgroundColor}}>
                <View>

                </View>
              </TouchableHighlight>

            </View>

        </View>
        </View>
    );
  }
}

const styles = StyleSheet.create({
  outercardview: {
    marginTop: (screenHeigth/2)-(screenWidth/2)-140,
    marginBottom: 20,
    marginRight: 10,
    marginLeft: 10,
    justifyContent: 'center',
    height:screenWidth,

    shadowOffset: {
      width: 2,
      height: 2,
    },
    shadowColor: 'grey',
    shadowOpacity: 0.1,
  }
});
AppRegistry.registerComponent('randomBackground', () => randomBackground);

标签: javascriptreactjsreact-nativestate

解决方案


由于您使用的backgroundColor: this.state.backgroundColor是所有按钮的颜色相同,因此您可以做的是维护一个变量,该变量保存您按下的按钮的当前索引/ID,并将背景颜色设置为 backgroundColor: this.state.activeButton===buttonid ?this.state.backgroundColor:''


推荐阅读