2016-04-11 20 views
1

私は最初のReactネイティブアプリケーションを開発しています。コンポーネントにIDを設定しようとしています。React Native:IDをコンポーネントに設定してこのコンポーネントのIDを取得

renderRow(rowData, sectionID, rowID){ 
    var past_matches_circles =[]; 
    for(var i=0; i<isPast; i++){ 
    past_matches_circles.push(
     <TouchableOpacity id={i} key = {i} collapsable={false} style={styles.small_circle} onPress={()=>this.pressOnCircle(rowData[`${i}`].MatchID)}> 
     </TouchableOpacity> 
    ); 
    } 
    return (
    <View> 
     <View style={{flexDirection:'row'}}> 
     {past_matches_circles} 
     </View> 
     <View style={{flexDirection:'row'}}> 
     <Image style={{width:100, height:100, margin:5}} source={{uri:'http://facebook.github.io/react/img/logo_og.png'}}/> 
     <View style={{justifyContent:'center', flex:1}}> 
      <Text> {rowData[0].MatchDate} </Text> 
      <Text> {rowData[0].HomeTeam} VS {rowData[0].AwayTeam} </Text> 
     </View> 
     </View> 
    </View> 
); 
} 
pressOnCircle(i){ 
    ToastAndroid.show('key ' + i, ToastAndroid.SHORT); 
} 

残念ながら、イテレータi値は常に私が押しています表示に関わらず、ループ内の最後の値に等しいです:コンポーネントのid

にこれは私がこれまで試したものです。

誰でもコンポーネントのIDを取得できますか?

答えて

4

数日後、最後にこの問題を解決しました。そして、私はこの質問に来る人のために投稿します。

iの値が常に同じになるように、ビューを返さずに配列にプッシュしていました。

私がやったように:役立つ

renderCircle(id) { 
    return <TouchableOpacity key={id} style={styles.small_circle} onPress={() => this.pressOnCircle(id)}> 
     </TouchableOpacity>; 
} 
renderRow(rowData, sectionID, rowID){ 
    var past_matches_circles =[]; 
    for(var i=0; i<isPast; i++){ 
    past_matches_circles.push(
     this.renderCircle(i) 
    ); 
    } 
    var { page, animationsAreEnabled } = this.state; 
    return (
    <View> 
     <View style={{flexDirection:'row'}}> 
     {past_matches_circles} 
     </View> 
     <View style={{flexDirection:'row'}}> 
     <Image style={{width:100, height:100, margin:5}} source={{uri:'http://facebook.github.io/react/img/logo_og.png'}}/> 
     <View style={{justifyContent:'center', flex:1}}> 
      <Text> {rowData[0].MatchDate} </Text> 
      <Text> {rowData[0].HomeTeam} VS {rowData[0].AwayTeam} </Text> 
     </View> 
     </View> 
    </View> 
); 
} 

希望。

1

.bindを使用して、iの値を超える新しい関数を作成できます。これは毎回新しい機能を作成しているので、パフォーマンスには最適ではありません。

onPress={ this.pressOnCircle.bind(this, i) }> 

また、あなたはハンドラ内で適切thisコンテキストを取得するには、コンストラクタで

this.pressOnCircle = this.pressOnCircle.bind(this); 

ような何かをする必要がある場合があります。

+0

答えてくれてありがとう、私は試しましたが、.bindを使用した後にonPressイベントはまったく起動しませんでした –

関連する問題