React Native应用中resultado变量无法显示的问题求助
React Native计算器界面不显示resultado的问题解决
问题核心是直接修改state属性不会触发组件重新渲染,你代码里两处直接修改state的操作导致界面无法更新:
this.state.operacion = "suma"_this.state.resultado = recibe
React规定必须通过setState()方法修改state,这样才能通知组件重新渲染,更新界面内容。
修正后的代码:
import React, {Component} from 'react'; import {View, Text, StyleSheet, TextInput, Button, Alert} from 'react-native'; export default class Login extends Component { constructor(props){ super(props); this.state = { num1: "", num2:"", operacion:"", resultado:"", }; } render(){ const btnSumaClick = () => { // 用setState修改operacion,确保state更新后再发起请求 this.setState({ operacion: "suma" }, () => { var xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = () => { if (xhttp.readyState == 4 && xhttp.status == 200) { console.log(xhttp.responseText); if (xhttp.responseText ==='0'){ Alert.alert("Error","Favor de ingresar dos numeros", [{text: "Accept", onPress: () => console.log("alert closed")}]); }else{ let recibe = xhttp.responseText; // 用setState更新resultado,触发组件重绘 this.setState({ resultado: recibe }); console.log(this.state.resultado); } } }; xhttp.open("GET", `https://proyecto150103.000webhostapp.com/Tarea1.php?num1=${this.state.num1}&num2=${this.state.num2}&operacion=${this.state.operacion}`, true); xhttp.send(); }); } return( <View style={styles.container}> <Text style={styles.titulo}>Calculadora </Text> <TextInput style={styles.input} placeholder="num1" onChangeText={num1 => this.setState({num1})} /> <TextInput style={styles.input} placeholder="num2" onChangeText={num2 => this.setState({num2})} /> <View style={styles.btnSuma}> <Button title="Suma" onPress={btnSumaClick} /> </View> <Text style={styles.titulo}> Resultado: {this.state.resultado} </Text> </View> ); } } const styles = StyleSheet.create({ btnSuma:{ width:100, height:80, marginLeft:150, marginTop:20, }, input:{ borderWidth:2, fontSize:25, marginTop:10, // 修正原代码拼写错误:margintTop -> marginTop color: `#000000`, }, titulo:{ fontSize:40, textAlign: "center", color: `#000000`, }, container:{ backgroundColor: `#ffb6c1`, flex: 1, // 让容器占满屏幕高度,避免内容显示不全 paddingTop: 50, // 避开状态栏遮挡顶部内容 }, })
额外优化说明:
- 修正了
input样式里的拼写错误margintTop为marginTop - 给
container添加flex:1和paddingTop,优化页面布局显示
内容的提问来源于stack exchange,提问作者Athziri Landazuri
相关产品推荐
相关产品推荐

