我正在构建一个井字游戏,需要知道如何为单个棋盘片添加个性化风格。如果我使用状态,我是否需要一个代表板上每个部分的变量?是否有更优雅的方式来做到这一点。我在这里发布了我的代码,只是让你知道它的外观。
import React, { Component } from 'react';
import { ListView, StyleSheet, Text, View, TouchableOpacity } from 'react-native';
class MainApp extends Component {
state = {
clicked: true,
spacePlayed: [],
tables: [0, 1, 2, 3, 4, 5, 6, 7, 8],
playedSpace: [],
}
searchBoard = (index) => {}
_setBoard = (tableId) => {
this.setState({
clicked: !this.state.clicked,
});
var spacePlayed = this.state.playedSpace.push(tableId);
this.setState({ spacePlayed });
}
buildBoard = () => {
var clicked = false;
return (this.state.tables.map((table, index) => {
if (index === 0) {
return (
<TouchableOpacity key={index} onPress={() => this._setBoard(index)}>
<View style={styles.table}></View>
</TouchableOpacity>
);
} else {
return (
<TouchableOpacity key={index} onPress={() => this._setBoard(index)}>
<View style={styles.tableActive}></View>
</TouchableOpacity>
);
}
}));
}
render() {
const active = this.state.clicked
? styles.active
: null;
return (
<View style={styles.container}>
{this.buildBoard()}
</View>
);
}
}
var styles = StyleSheet.create({
container: {
flexWrap: 'wrap',
flexDirection: 'row',
width: 200,
justifyContent: 'center',
alignItems: 'center',
marginLeft: 70,
marginTop: 20,
},
table: {
height: 50,
width: 50,
backgroundColor: '#78BEC5',
margin: 5,
justifyContent: 'center',
alignItems: 'center',
},
active: {
backgroundColor: '#ECAF4F',
},
tableActive: {
height: 50,
width: 50,
backgroundColor: '#ECAF4F',
margin: 5,
justifyContent: 'center',
alignItems: 'center',
},
});
export default MainApp;