gpt4 book ai didi

javascript - 单独 react native onPress TouchableHighlights 吗?

转载 作者:行者123 更新时间:2023-12-02 22:50:30 24 4
gpt4 key购买 nike

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

如果我单击按钮,则只有该按钮应该更改其颜色,但目前所有按钮都会更改相同的颜色。有人知道如何解决这个问题吗?

我不知道如何单独处理每个 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:''

关于javascript - 单独 react native onPress TouchableHighlights 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58198218/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com