javascript - 单独反应原生 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);
解决方案
由于您使用的backgroundColor: this.state.backgroundColor
是所有按钮的颜色相同,因此您可以做的是维护一个变量,该变量保存您按下的按钮的当前索引/ID,并将背景颜色设置为 backgroundColor: this.state.activeButton===buttonid ?this.state.backgroundColor:''
推荐阅读
- excel - Excel IF 语句涉及日期
- ios - 为什么 UIVisualEffectView 在 SwiftUI 上下文菜单中不起作用?
- python - 如何在 Firebase 云功能中安装 TensorFlow
- spring-data - 如何在 Spring Data / Webflux 中使用可选属性
- shell - 为什么 conda 没有在这个 shell 脚本中激活我的环境?
- c++ - C ++:使用使用其默认构造函数的临时对象进行初始化声明函数原型而不是变量
- c# - 如何在 DirectShow.Net 中访问网络摄像头的电力线补偿和背光补偿设置
- c# - 如果在 MVC Core 3.1 中使用 asp-for 属性,则在 POST 之后不设置该值
- compilation - 编译会使 SSD 降级多少?
- laravel - 如何在单个查询中找到多列总和的总和