React Nativeの練習として、複数のボタンがありボタンを押すと対応したデータをsetState()で更新してStyleを切り替え、そのボタンの色が変化するようなアプリを作っています。
コードは以下です。
JavaScript
1import React, { Component } from 'react'; 2import { AppRegistry, StyleSheet, Text, View, TouchableHighlight } from 'react-native'; 3 4//Gameコンポーネント 5export default class Game extends Component { 6 constructor(props) { 7 super(props); 8 //ボタンの色を決めるフラグ 9 this.state = {data: initialData}; 10 } 11 12 //ボタンが押された際の処理(対応するフラグをfalseにセットする) 13 _onPress(num) { 14 let data = Array.from(this.state.data); 15 idx = 'box' + num.toString(); 16 data.idx = false; 17 this.setState({ 18 data: data, 19 }); 20 } 21 22 render() { 23 return ( 24 <View style={styles.row}> 25 26 <View style={styles.box}> 27 <TouchableHighlight key='box1' onPress={ () => this._onPress(1)} style={this.state.data.box1 ? styles.box2 : styles.box3}> 28 <Text>a</Text> 29 </TouchableHighlight> 30 </View> 31 32 <View style={styles.box}> 33 <TouchableHighlight key='box2' onPress={ () => this._onPress(2)} style={this.state.data.box2 ? styles.box2 : styles.box3}> 34 <Text>a</Text> 35 </TouchableHighlight> 36 </View> 37 38 <View style={styles.box}> 39 <TouchableHighlight key='box3' onPress={ () => this._onPress(3)} style={this.state.data.box3 ? styles.box2 : styles.box3}> 40 <Text>a</Text> 41 </TouchableHighlight> 42 </View> 43 44 <View style={styles.box}> 45 <TouchableHighlight key='box4' onPress={ () => this._onPress(4)} style={this.state.data.box4 ? styles.box2 : styles.box3}> 46 <Text>a</Text> 47 </TouchableHighlight> 48 </View> 49 50 </View> 51 ); 52 } 53} 54 55const styles = StyleSheet.create({ 56 row: { 57 flex: 1, 58 flexDirection: 'row', 59 justifyContent: 'space-between', 60 }, 61 box: { 62 width: 65, 63 height: 65, 64 alignItems:'center', 65 justifyContent:'center', 66 backgroundColor: 'steelblue', 67 }, 68 box2: { 69 width: 60, 70 height: 60, 71 backgroundColor: 'powderblue', 72 }, 73 box3: { 74 width: 60, 75 height: 60, 76 }, 77}); 78 79const initialData = { 80 box1: true, 81 box2: true, 82 box3: true, 83 box4: true, 84} 85 86AppRegistry.registerComponent('Game', () => Game); 87
このコードだと、最初の表示は正しくされるのですが、一つのボタンを押した瞬間に全てのボタンが同時にfalseの状態になってしまう現象が起こっており、解決方法を教えていただきたいです。初心者なので良いコードとなっておらずすみません。
回答2件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2017/05/23 08:42