auの日記

プログラミング初心者の日記。(auはハンドルネームです)

React Nativeで一つ前のネストの値を使う方法

auです。

React Nativeで以下のようなデータをButtonの遷移で、次の値に行くときに困ったのでメモ程度に残しておこうと思います。

var questions = [
    {
        num: '第1問',
        question: 'クイズ名',
        answers: [
            {id: '1', text: 'テキスト1'},
            {id: '2', text: 'テキスト2'},
            {id: '3', text: 'テキスト3'},
            {id: '4', text: 'テキスト4', correct: true}
        ],
        correct: '④',
        description: '解説' // ここをボタンの遷移先で表示したい
    }
]

2つスクリーンがあり、最初のスクリーンではこのようにボタンを定義しています。

{this.props.navigation.state.params.answers.map(
      data => {return (<Button title={data.text} onPress={() => {this.props.navigation.navigate('Answer', 
      this.props.navigation.state.params)}}></Button>)})}

map関数を使って、answersのテキストをボタンにしています。

2つ目のスクリーンでは、このようにdescriptionを表示しています。

<Text style={styles.textStyle}>{this.props.navigation.state.params.discription}</Text>


1つ目のスクリーンでは

{this.props.navigation.state.params.answers.map(
      data => {return (<Button title={data.text} onPress={() => {this.props.navigation.navigate('Answer', 
      <span style="color: #ff0000">data</span>)}}></Button>)})}

としていたのですが、これだと辞書型より下のネストにしかアクセスできなくなってしまったので、全てのデータを渡すために、最初のように書いたらうまくいきました。