我正在学习React Native,并且试图建立一个简单的“问题和答案”表格。我已经为某些文本设置了一个值,并且当onPress
被触发时,它应该将其值恢复为状态:
import React, { Component } from 'react';
import { View, Text } from 'react-native';
class quest extends Component {
state = {
question1: ans1, //where ans1 is the value onPressed
question2: ans1, //where ans3 is the value onPressed
longitude: 0.3256, //geolocation
latitude: -0.3589,//geolocation
}
onSubmit = () => (
console.log(this.state)
)
render() {
return (
<View>
<text> What kind of ball is this?</text>
<TouchableHighlight onPress={//get this value}>
<text> ans1 value='basketball'</text>
<TouchableHighlight />
<TouchableHighlight onPress={//get this value}>
<text> ans2 value='football'</text>
<TouchableHighlight />
<TouchableHighlight onPress={//get this value}>
<text> ans3 value='handball'</text>
<TouchableHighlight />
<text> What kind of vehicle is this?</text>
<TouchableHighlight onPress={//get this value}>
<text> ans1 value='bike'</text>
<TouchableHighlight />
<TouchableHighlight onPress={//get this value}>
<text> ans2 value='bus'</text>
<TouchableHighlight />
<TouchableHighlight onPress={//get this value}>
<text> ans3 value='train'</text>
<TouchableHighlight />
<button title='Submit' onPress={onSubmit} />
</View>
)
}
}
答案 0 :(得分:1)
我无法理解您的问题。我想您是在问如何将文本的价值保存为状态。如果是的话,那么就可以了
<TouchableHighlight onPress={() => this.setState({question1: 'bike',})}>
<text> ans1 value='bike'</text>
<TouchableHighlight/>
答案 1 :(得分:1)
尝试一下:
constructor(props) {
super(props)
this.state = {
question1: '',
question2: '',
}
}
render() {
return (
<View style={styles.container}>
<Text style={styles.answers}> What kind of ball is this? </Text>
<TouchableHighlight onPress={() => this.setState({ question1: 'Basketball' })}>
<Text> Basketball</Text>
</TouchableHighlight>
<TouchableHighlight onPress={() => this.setState({ question1: 'Football' })}>
<Text> Football</Text>
</TouchableHighlight>
<TouchableHighlight onPress={() => this.setState({ question1: 'Volleyball' })}>
<Text style={styles.answers}> Volleyball</Text>
</TouchableHighlight>
<Text style={styles.answers}> What kind of vehicle is this? </Text>
<TouchableHighlight onPress={() => this.setState({ question2: 'Bike' })}>
<Text> Bike</Text>
</TouchableHighlight>
<TouchableHighlight onPress={() => this.setState({ question2: 'Bus' })}>
<Text> Bus</Text>
</TouchableHighlight>
<TouchableHighlight onPress={() => this.setState({ question2: 'Train' })}>
<Text style={styles.answers}> Train</Text>
</TouchableHighlight>
<Button
title='Submit'
onPress={() => console.log(this.state)}
/>
</View>
)
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
marginTop: 50,
marginLeft: 20
},
answers: {
marginBottom: 15,
},
})