You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

122 lines
3.2 KiB

import React from "react"
import { View, StyleSheet, StatusBar, Text, SafeAreaView } from "react-native"
import { Button, ButtonContainer } from "../components/Button"
import { Alert } from "../components/Alert"
const styles = StyleSheet.create({
container: {
backgroundColor: "#36B1F0",
flex: 1,
paddingHorizontal: 20
},
text: {
color: "#fff",
fontSize: 25,
textAlign: "center",
letterSpacing: -0.02,
fontWeight: "600"
},
safearea: {
flex: 1,
marginTop: 100,
justifyContent: "space-between"
}
})
class Quiz extends React.Component {
state = {
correctCount: 0,
totalCount: this.props.navigation.getParam("questions", []).length,
availableIds: this.props.navigation.getParam("questions", []).map(a => a.id),
activeQuestionId: this.props.navigation.getParam("questions", [])[
Math.floor(Math.random() * this.props.navigation.getParam("questions", []).length)
].id,
answered: false,
answerCorrect: false
}
answer = correct => {
this.setState(
state => {
const nextState = { answered: true }
if (correct) {
nextState.correctCount = state.correctCount + 1
nextState.answerCorrect = true
} else {
nextState.answerCorrect = false
}
return nextState
},
() => {
setTimeout(() => this.nextQuestion(), 750)
}
)
}
nextQuestion = () => {
this.setState(state => {
const updatedIndexes = state.availableIds.filter( item => item != state.activeQuestionId)
const nextId = updatedIndexes[Math.floor(Math.random() * updatedIndexes.length)]
if (!updatedIndexes.length) {
this.props.navigation.popToTop()
}
/*
if (nextIndex >= state.totalCount) {
this.props.navigation.popToTop()
}*/
return {
totalCount: updatedIndexes.length,
availableIds: updatedIndexes,
activeQuestionId: nextId,
answered: false
}
})
}
render() {
const questions = this.props.navigation.getParam("questions", [])
const question = questions.filter(item => item.id == this.state.activeQuestionId)[0] || questions[0]
return (
<View
style={[
styles.container,
{ backgroundColor: this.props.navigation.getParam("color") }
]}
>
<StatusBar barStyle="light-content" />
<SafeAreaView style={styles.safearea}>
<View>
<Text style={styles.text}>{question.question}</Text>
<ButtonContainer>
{question.answers.map(answer => (
<Button
key={answer.id}
text={answer.text}
onPress={() => this.answer(answer.correct)}
/>
))}
</ButtonContainer>
</View>
<Text style={styles.text}>
{`${this.state.correctCount}/${this.state.totalCount} - ${this.state.availableIds.join(',')} `}
</Text>
</SafeAreaView>
<Alert
correct={this.state.answerCorrect}
visible={this.state.answered}
/>
</View>
)
}
}
export default Quiz