правильное использование функции обратного вызова в реагировать родной - PullRequest
1 голос
/ 14 апреля 2020

Отказ от ответственности: Довольно новичок в javascripting и response-native:)

Я пытаюсь очень простое приложение в реагировать родной. Пользователь получает экран с двумя цифрами и оператором (например, +, - и т. Д. c), и пользователь вводит результат в предоставленном текстовом поле. Как на скриншоте ниже

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) Самое главное, как я могу переместить кнопку в свой родительский класс и каким-то образом вернуть результат своему родителю из дочернего класса?

2) Мои поля TextInput в не очищаются при восстановлении чисел. Что здесь не так?

1 Ответ

0 голосов
/ 14 апреля 2020

Вам необходимо использовать метод UNSAFE_componentWillReceive в дочернем компоненте, когда значение родительского компонента изменяется

...