在React Native中正确使用回调函数

时间:2020-04-14 00:28:54

标签: javascript reactjs react-native react-redux

免责声明:javascript和react-native的新手:)

我正在尝试使用本机响应一个非常简单的应用程序。向用户显示一个屏幕,该屏幕上有两个数字和一个运算符(例如+,-等),用户将在提供的文本字段中输入结果。如下面的屏幕截图

enter image description here

为方便应用,我有两个主要的类:

1)父类(基本上生成数字,作为道具传递给孩子,在回调函数中获取结果,如果结果正确,则再次重新生成数字)

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

import BasicBox from '../components/BasicBox';


export default class example extends Component {

  constructor() {
    super();
    this.state = {
      result: 0
    };
    this.generate()
  }

  getResponse(result){
    let text=""
    for (var i = 0; i < result.length; i++) {
      text += result[i];
    }
    console.log(result)
    if (this.expected_result === parseInt(text))
    {
      this.generate()
    }
    this.setState({result:parseInt(text)})
  }

  generate() {
    this.length = 3
    this.number_1 = Math.floor(Math.random() * 1000)
    this.number_2 = Math.floor(Math.random() * 1000)
    this.result_box_count =  this.length + 1
    this.operator="+"
    this.expected_result = eval (this.number_1 + this.operator + this.number_2)

    console.log(this.number_1)
    console.log(this.number_2)
    console.log(this.expected_result)
    // this.setState({result:this.expected_result})
  }

  render() {
    //this.generate();

    return (
      <View>
        <BasicBox 
          number_1={this.number_1} 
          number_2={this.number_2} 
          operator={this.operator}
          result_box_count={this.result_box_count}
          get_result = {this.getResponse.bind(this)}
        />

        <Text>
          {console.log(this.expected_result)}
          {console.log(this.state.result)}
          {this.state.result===this.expected_result ? "": "Oh Boy!" }
        </Text>
      </View>
    );
  }
}

2)子类(按父级生成的数字,并在按下按钮时将结果返回给父级)

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


export default class BasicBox extends Component {
    constructor() {
        super();
        this.state = {
            result: ["","","",""]
        };
    }

    render(){
        return (<View>
            <View style={styles.main}>
                <View>
                    <View style={styles.operand}>
                        <Text style={styles.digit}>{Math.floor(this.props.number_1/100)}</Text>
                        <Text style={styles.digit}>{Math.floor(this.props.number_1/10%10)}</Text>
                        <Text style={styles.digit}>{this.props.number_1%10}</Text>
                    </View>
                    <View style={styles.operand}>
                        <Text style={styles.digit}>{Math.floor(this.props.number_2/100)}
                        </Text>
                        <Text style={styles.digit}>{Math.floor(this.props.number_2/10%10)}</Text>
                        <Text style={styles.digit}>{this.props.number_2%10}</Text>
                    </View>
                    <View style={styles.operand}>
                        <View>
                            <Text style={styles.digit_hidden} >1</Text>
                            <TextInput style={styles.digit_answer} 
                                    keyboardType='numeric' 
                                    maxLength={1}
                                    onChangeText={(txt)=>{
                                        result=this.state.result;
                                        result[0]=txt
                                        this.setState({result:result})
                                    }}
                                    >

                            </TextInput>
                        </View>
                        <View>
                            <Text style={styles.digit_hidden}>1</Text>
                            <TextInput style={styles.digit_answer} 
                                    keyboardType='numeric' 
                                    maxLength={1}
                                    onChangeText={(txt)=>{
                                        result=this.state.result;
                                        result[1]=txt
                                        this.setState({result:result})
                                    }
                                    }

                                >

                            </TextInput>
                        </View>
                        <View>
                            <Text style={styles.digit_hidden}>1</Text>
                            <TextInput style={styles.digit_answer} 
                                    keyboardType='numeric' 
                                    maxLength={1}
                                    onChangeText={(txt)=>{
                                        result=this.state.result;
                                        result[2]=txt,
                                        this.setState({result:result})
                                    }}
                                    ></TextInput>
                        </View>
                        <View>
                            <Text style={styles.digit_hidden}>1</Text>
                            <TextInput style={styles.digit_answer} 
                                    keyboardType='numeric' maxLength={1}
                                    onChangeText={(txt)=>{
                                        result=this.state.result;
                                        result[3]=txt,
                                        this.setState({result:result})
                                    }}
                            ></TextInput>
                        </View>
                    </View>

                </View>
                <View>
                    <Text style={styles.digit}>{this.props.operator}</Text>
                </View>
            </View>

            <Button onPress={()=>{this.props.get_result(this.state.result)}}
                title="Check Result"
            />
        </View>) 
    }
}


const styles = StyleSheet.create ({
    main: {
        flexDirection:"row",
        // borderWidth:1,
        // flex: 1,
        justifyContent: "center",
        // alignItems: "center"
    },
    digit: {
        fontSize: 80,
        // borderWidth:1,
        //adjustsFontSizeToFit
    },
    digit_hidden: {
        fontSize: 80,
        // borderWidth:1,
        flex:1,


        // color: `rgb(255,255,255)`
    },
    operand: {
        flexDirection:"row",
        justifyContent:"flex-end",
        // alignItems:"flex-end",
        // borderWidth:1,
    },
    digit_answer: {
        // alignItems:"baseline",
        // flexDirection:"row",
        // justifyContent:"flex-end",

        // backgroundColor: `rgb(255,255,255)`,

        // alignItems:"flex-end",
        fontSize: 80,
        // backgroundColor: gray`rgb(255,255,255)`,
        backgroundColor:'gray',
        borderWidth:1,
    },
});

感谢您到目前为止的阅读:)

在我的类定义中,Button在我的子类中,因为我想在OnPress中将结果发送给父类。对于用户界面,我的问题是:

1)最重要的是,如何将Button移动到父类,并以某种方式将结果从子类返回给父类?

2)重新生成数字时,不会清除中的我的TextInput字段。怎么了?

1 个答案:

答案 0 :(得分:0)

父组件值更改时,您需要在子组件中使用UNSAFE_componentWillReceive方法