2017-08-17 70 views
0

我想使它,以便我可以单击按钮并转到我的json文件中的下一个对象。但我不确定如何继续单击for循环。我试图添加一个i ++到按钮中的onpress事件,但这不起作用,只是错误,因为我认为在新闻界需要一个功能。任何帮助将是太棒了!我是很新的反应本土很抱歉,如果这个心不是做反应原生迭代通过对象后按钮单击

import React, { Component } from 'react'; 
import { 
    AppRegistry, 
    StyleSheet, 
    Text, 
    View, 
    Image, 
    Button 
} from 'react-native'; 

var jsonData = require('./skull.json'); 

export default class flashcards extends Component { 
    render() { 
     var i = 0; 

     for (i; i < 50; i++) { 
      var skull = jsonData[i]; 
      return (
       <View style={styles.container}> 
        <Text> 
         Question #{jsonData.quiz.question[i].number} 
        </Text> 

        <Text> 
         {jsonData.quiz.question[i].question} 
        </Text> 
        <Image 
         source={{ uri: jsonData.quiz.question[i].picture }} 
         style={styles.thumbnail} 
        /> 
        <Button 
         title="Next Question" 
         color="#841584" 
         accessibilityLabel="Learn more about this purple button" 
        /> 
       </View> 
      ); 
     } 
    } 
} 

var styles = StyleSheet.create({ 
    container: { 
     flex: 1, 
     justifyContent: 'center', 
     alignItems: 'center', 
     backgroundColor: '#F5FCFF' 
    }, 
    thumbnail: { 
     width: 300, 
     height: 350 
    } 
}); 

AppRegistry.registerComponent('flashcards',() => flashcards); 
+0

我觉得你的方法是错误的。我认为你应该使用Navigator。更多细节:https://facebook.github.io/react-native/releases/0.23/docs/navigator.html – Dev

+0

创建一个状态变量,用于跟踪哪个是currentItem,当按下时它将currentItem状态变量设置为当前的一个,应该显示。 – fungusanthrax

回答

0

雅的方式,我认为你需要创建state增加你的i,并设置你的onPress事件这样的状态:

export default class flashcards extends Component { 
    constructor(props) { 
    super(props); 
    this.state = {i: 0}; 
    } 

    onButtonPress =() => { 
    if(this.state.i < 50){ 
     this.setState({ 
     i: this.state.i + 1 
     }); 
    } 
    } 

    render() { 
    return (
     <View style={styles.container}> 

     ....//your code 

     <Button 
      onPress={this.onButtonPress} 
      title="Next Question" 
      color="#841584" 
      accessibilityLabel="Learn more about this purple button" 
     /> 

     </View> 
    ); 
    } 
} 

,并呼吁JSON数据,你必须改变ithis.state.i这样的:

jsonData.quiz.question[this.state.i].question

欲了解更多的细节,你必须了解state对原生反应,你可以在documentation阅读。我希望这个答案可以帮助你。

+0

那怎么样@ A.Hill,这工作? –

0

你需要做的是这样,因为this.setState将导致50倍当您在循环做this.setState重新渲染

export default class flashcards extends Component { 
    constructor(props) { 
    super(props); 
    this.state = {i: 0}; 
    } 

    onButtonPress =() => { 
    let val = this.state.i; 
    if(val < 50){ 
     va += 1 
    } 
    this.setState({ i: val }); 
    } 

    render() { 
    return (
     <View style={styles.container}> 

     ....//your code 

     <Button 
      onPress={this.onButtonPress} 
      title="Next Question" 
      color="#841584" 
      accessibilityLabel="Learn more about this purple button" 
     /> 

     </View> 
    ); 
    } 
}