【发布时间】:2016-11-17 13:15:42
【问题描述】:
我正在制作一个反应原生的测验应用程序,我用 PHP 编写了一个 API,它从数据库中获取问题和选项,来自 API 的响应看起来像
[{"id":2109,
"title":"\u0915\u0930\u094d\u0923\u093e\u0932\u0940 \u0928\u0926\u0940\u0915\u094b \u0938\u0939\u093e\u092f\u0915 \u0928\u0926\u0940 \u0924\u0932\u0915\u093e \u092e\u0927\u094d\u092f\u0947 \u0915\u0941\u0928 \u0939\u094b\u0907\u0928 ?",
"option":[{
"option_id":191061,
"options":"\u0939\u0941\u092e\u094d\u0932\u093e \u0915\u0930\u094d\u0923\u093e\u0932\u0940",
"correct":0
},
{
"option_id":191062,
"options":"\u0920\u0942\u0932\u094b \u092d\u0947\u0930\u0940",
"correct":0},
{
"option_id":191060,
"options":"\u092e\u0941\u0917\u0941 \u0915\u0930\u094d\u0923\u093e\u0932\u0940",
"correct":0
},{
"option_id":191059,
"options":"\u0921\u094b\u0932\u094d\u092a\u093e \u0915\u0930\u094d\u0923\u093e\u0932\u0940",
"correct":1
}
]}]
................................
等等,
到目前为止,我已经按照我喜欢的方式成功地在我的 react 应用程序中获取了 json。但是现在我只想为每个问题选择一个选项,我希望根据用户选择突出显示该选项,我还必须通过验证 json 响应来检查用户是否正确。
我怎样才能做到这一点?
完整代码在这里:
import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
Text,
View,
TouchableHighlight,
Alert,
Navigator,
WebView,
ScrollView,
ListView
} from 'react-native';
export default class Api extends Component{
constructor(){
super()
this.state = {
id:'',
option_id:'',
option_option:[],
options_ans:[],
title:'',
data:[],
userSelectedIndex:-1,
}
}
componentWillMount(){
fetch('http://192.168.1.11/loksewaquiz/index.php? exam_of=kharidar', {method: 'GET'})
.then((response) => response.json())
.then((responseData) =>{
this.setState({
data:responseData,
})
})
.done();
}
onUserSelectedOption(index){
this.setState({
userSelectedIndex:index,
});
}
render(){
const result = this.state.data.map((data) =>{
const xx = data.ans_option.map((ans_option,index)=>{
return (
<TouchableHighlight onPress={()=> this.onUserSelectedOption(ans_option, index)}>
<Text key={ans_option.option_id} style={{backgroundColor: (index === this.state.userSelectedIndex) ? 'red' : 'transparent'}}> {ans_option.option_option}</Text>
</TouchableHighlight>
)
})
return(
<View>
<Text style={styles.titles}>{data.title}</Text>
{xx}
</View>
)
})
return(
<ScrollView>
{result}
</ScrollView>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
flexDirection:'row',
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
},
button:{
backgroundColor:'#EEE',
padding:10,
marginRight:5,
marginLeft:5,
},
options:{
padding:10,
marginRight:5,
marginLeft:5,
backgroundColor:'#EEE',
},
titles:{
backgroundColor:'#000',
color:'#FFF',
},
selectedoptions:{
backgroundColor:'#008000',
}
});
【问题讨论】:
-
option 应该是这个方法的第一个参数 onUserSelectedOption(option, index){ this.setState({ userSelectedIndex:index, }); }
-
不完全是,它会突出显示所有选项,例如:如果我单击问题 1 的选项 1,它也会突出显示所有问题的选项 1,并且突出显示也不是持久的。我将在上面添加一张图片以澄清结果。
-
以上图片是我更新代码后拍摄的。谢谢
标签: php json multidimensional-array react-native