react native-使用react挂钩在子组件中通知状态更新的父组件?

时间:2020-04-09 22:08:40

标签: javascript react-native state

我目前正在尝试基于对子类组件所做的更改来更新我的父功能组件内的react native hook状态。我一直在研究并尝试各种解决方案,但还没有找到与功能和类组件有关的解决方案。以下是我的代码,应执行的操作,遇到的错误以及尝试的操作。

应该做什么

  1. 概述卡上有一个按钮,可让您添加卡片。
  2. AddCard允许您填写一些TextInput框
  3. AddCard应该允许您按下保存按钮,并返回到“概述卡”屏幕。
  4. 用户在第2步中填写的信息应显示在“概述卡”屏幕上。

我陷入了步骤4。

App.js

import React, { useState } from 'react';
import { StyleSheet, Text, TextInput, View, Button, TouchableOpacity, ShadowPropTypesIOS } from 'react-native';
import AddCard from './components/AddCard.js';
import { NavigationContainer } from '@react-navigation/native';
import { createStackNavigator } from '@react-navigation/stack';
import { useNavigation } from '@react-navigation/native';

// function returnData(id, firstTwo, lastFour, recentAmount) {
//   this.setState({id: id, firstTwoDigits: firstTwo, lastFourDigits: lastFour, currentAmt: recentAmount});
// }

function HomeScreen({ navigation }) {
  const [id, setID ] = useState(0);
  // const [firstTwo, setFirstTwoDigits] = useState(0);
  const [lastFour, setLastFourDigits] = useState(0);
  const [recentAmount, setRecentAmount] = useState(0);
  return (
    <View style={styles.homeContainer}>
      <Button title="Add Card" onPress={() => navigation.navigate('Add Card')}/>
      <Text>
      CardID: {id}
      </Text>
      <Text>
      Last Four Digits: {lastFour}
      </Text>
      <Text>
      Current Amount: {recentAmount}
      </Text>
      <Text style={styles.textStyle} >VISA xxxx</Text>
      <Text style={styles.textStyle}>MASTERCARD xxxx</Text>
      <Text style={styles.textStyle}>AMEX xxxx</Text>
    </View>
  );
}

function AddCardScreen({ navigation }) {
  return (
    <View style={styles.addCardContainer}>
      <AddCard 
      navigation={navigation}
      id={id}
      // firstTwo={firstTwo}
      // lastFour={lastFour}
      // recentAmount={recentAmount} 
      />
    </View>
  );
}

const Stack = createStackNavigator();

function App() {
  return (
    <NavigationContainer>
      <Stack.Navigator>
        <Stack.Screen name="Home" component={HomeScreen} options={{ title: 'Overview Cards' }} />
        <Stack.Screen name="Add Card" component={AddCardScreen} />
      </Stack.Navigator>
    </NavigationContainer>
  );
}
// function AddCardButton(){
//       return (
//           <View style={styles.buttonContainer}>
//               <TouchableOpacity>
//                   <Text style={styles.button}>Add Card</Text>
//               </TouchableOpacity>
//           </View>
//       );
//   }

export default App;

const styles = StyleSheet.create({
  homeContainer: {
    flex: 1,
    backgroundColor: '#ef95b1',
    alignItems: 'center',
    justifyContent: 'flex-start',
  },
  addCardContainer: {
    flex: 1,
    backgroundColor: '#28cdf0',
    justifyContent: 'flex-start',
  },
  buttonContainer: {
    flexDirection: 'row',
    alignSelf: 'flex-end',
    marginTop: 15,
  },
  button: {
    flexDirection: 'row',
    alignSelf: 'flex-end',
    marginTop: 15,
    right: 10,
    backgroundColor: '#2565ae',
    borderWidth: 1,
    borderRadius: 12,
    color: 'white',
    fontSize: 15,
    fontWeight: 'bold',
    overflow: 'hidden',
    padding: 10,
    textAlign:'center',
  },
  textStyle: {
    padding: 10,
  }
});

AddCard.js

import React, { Component } from 'react';
import { StyleSheet, View, Text, TextInput, TouchableOpacity } from 'react-native';
import { Input } from 'react-native-elements'
import { ScrollView } from 'react-native-gesture-handler';
// import { loadSettings, saveSettings } from '../storage/settingsStorage';

class AddCardScreen extends Component {
   constructor(props) {
    super(props);
    this.state = {
        firstTwo  : '',
        lastFour  : '',
        recentAmt : ''
    };

    this.addFT = this.addFT.bind(this)
    this.addLF = this.addLF.bind(this)
    this.addRecAmt = this.addRecAmt.bind(this)
   }

   static navigationOptions = {
       title: 'Add Card'
    };

   addFT(firstTwo) {
    this.setState(Object.assign({}, this.state.firstTwo, { firstTwo }));
  }

  addLF(lastFour) {
    this.setState(Object.assign({}, this.state.lastFour, { lastFour }));
  }

  addRecAmt(recentAmt) {
    this.setState(Object.assign({}, this.state.recentAmt, { recentAmt }));
  }

   handleSubmit() {
    const { navigation } = this.props;
    alert('New card saved. Returning to Home to view addition.');
    // navigation.state.params.returnData('123', this.firstTwo, this.lastFour, this.recentAmt);
    navigation.navigate('Home', this.firstTwo, this.lastFour, this.recentAmt);
  }

    render() {
        const {navigation} = this.props;
        return (
            <ScrollView>
                <View style={styles.inputContainer}>
                    <TextInput 
                    style={styles.textInput}
                    placeholder="First two digits of card"
                    placeholderTextColor="#000000"
                    keyboardType={'number-pad'}
                    maxLength = {2}

                    // onChangeText={this.addFT}
                    // inputValFT={this.state.firstTwo}
                    />
                    <TextInput
                    style={styles.textInput}
                    placeholder="Last four digits of card"
                    placeholderTextColor="#000000"
                    keyboardType={'number-pad'}
                    maxLength = {4}

                    // onChangeText={this.addLF}
                    // inputValLF={this.state.lastFour}
                    />
                    <TextInput
                    style={styles.textInput}
                    placeholder="Most recent dollar amount"
                    placeholderTextColor="#000000"
                    keyboardType={'decimal-pad'}

                    // onChangeText={this.addRecAmt}
                    // inputValRA={this.state.recentAmt}
                    />
                </View>
                <View style={styles.inputContainer}>
                    <TouchableOpacity 
                    style={styles.saveButton}
                    onPress={this.handleSubmit.bind(this)}>
                        <Text style={styles.saveButtonText}>Save</Text>
                    </TouchableOpacity>
                </View>
            </ScrollView>
        );
    }
}
// () => navigation.navigate('Home') line 81
export default AddCardScreen;

const styles = StyleSheet.create({
    inputContainer: {
        paddingTop: 15
      },
      textInput: {
        borderColor: '#FFFFFF',
        textAlign: 'center',
        borderTopWidth: 1,
        borderBottomWidth: 1,
        height: 50,
        fontSize: 17,
        paddingLeft: 20,
        paddingRight: 20
      },
      saveButton: {
        borderWidth: 1,
        borderColor: '#007BFF',
        backgroundColor: '#007BFF',
        padding: 15,
        margin: 5
      },
      saveButtonText: {
        color: '#FFFFFF',
        fontSize: 20,
        textAlign: 'center'
      }

});

我尝试过的事情:

  1. 我尝试将React Hook添加到我的父组件HomeScreen。我添加了const [id, setID] = useState(0);,依此类推。然后,我调用了<Text>内部的三个return()中的对象。我尝试添加id = {id},以此类推(您可以看到其余部分已被注释掉。起初,这些部分没有被注释掉,但是我遇到了错误:Can't find variable: firstTwo。应用程序将不会存在此错误时完全不会加载。
  2. 我注意到我根本没有使用AddCard.js中的addFT, addLF, and addRecAmt函数(因为我评论了它们被调用的部分,因为它不起作用),我认为这可能是一个问题太。我将它们添加到handleSubmit()

像这样:

handleSubmit(firstTwo, lastFour, recentAmt) {
    const { navigation } = this.props;
    this.addFT(firstTwo);
    this.addLF(lastFour);
    this.addRecAmt(recentAmt);
    alert('New card saved. Returning to Home to view addition.');
    // navigation.state.params.returnData('123', this.firstTwo, this.lastFour, this.recentAmt);
    navigation.navigate('Home', this.firstTwo, this.lastFour, this.recentAmt);
  }

我必须将id = {id}注释掉,因为如果不这样注释,那么在取消注释时会产生与firstTwo相同的错误。通过对App.js和AddCard.js进行此更改,应用程序可以很好地加载。我认为这可能是我想去的正确路线,但我不确定从这里去哪里。

1 个答案:

答案 0 :(得分:1)

因此,您通常是对的,在handleSubmit中,应使用参数(其他步骤数据)导航到Home屏幕

handleSubmit(firstTwo, lastFour, recentAmt) {
  ...
  navigation.navigate('Home', {
    firstTwo: this.state.firstTwo,
    lastFour: this.state.lastFour,
    recentAmt: this.state.recentAmt,
  });
}

现在Home屏幕将显示带有参数的道具route

function HomeScreen({ route }) {
  const { firstTwo, lastFour, recentAmt } = route.params || {}; // in case we have no params it is undefined by the default

  const [lastFour, setLastFourDigits] = useState(lastFour || ''); // using it as a default value for our state variable
  ...
}

让我知道它是否有帮助;)