将数据从功能组件传递到父类组件的反应是本机的

时间:2020-10-07 18:54:39

标签: javascript reactjs react-native

所以我的应用程序中有一个选项卡导航,我试图从选项卡屏幕中的一个扫描屏幕上扫描一个UPC编号,称为ScanScreen,并将其发送到主屏幕,该屏幕上有一个搜索栏,并且我希望upc编号导航完成后显示在此处。到目前为止,我已经能够扫描upc号码并导航到homeScreen,但是由于某种原因,我无法发送upc号码。我曾尝试过多种方法。 navigation.navigate('HomeScreen',{upc:data})和主屏幕上的getParam(),但无济于事。

Obj =扫描upc,然后成功导航到homeScreen选项卡并在searchBar上显示数字

    export default class HomeScreen extends React.Component {

  constructor(props) {
    super(props);
    this.state = { search: '', isLoading: true };
    this.products = [];
  }

  componentDidMount() {
    
    db.collection("products")
      .get()
      .then(querySnapshot => {
        const data = querySnapshot.docs.map(doc => doc.data());

        this.setState({
          products: data,
          isLoading: false,
          dataSource: data
        },
          function () {
            this.products = data;
          }
        );
      }).catch(error => {
        console.error(error);
      });

      
 
  }

  GetFlag(ingredients, status) {
    var Ingredients = Object.values(ingredients);
    for (var i = 0; i < Ingredients.length; i++) {
      if (Ingredients[i].Status == status)
        return true;
      
    }
  }

  search = text => {
    console.log(text);
  };
  clear = () => {
    this.search.clear();
  };
  SearchFilterFunction(text) {
    const newData = this.products.filter(function (item) {
      const itemData = item.Name ? item.Name.toUpperCase() :
        ''.toUpperCase();
      const upcData = item.UPC;
      const textData = text.toUpperCase();
      if (itemData.indexOf(textData) > -1)
        return true;
      else if (upcData.toString().indexOf(textData) > -1)
        return true;
      else
        return false;

    });
    this.setState({
      dataSource: newData, search: text,
    });

  }
  ListViewItemSeparator = () => {
    return (
      <View
        style={{
          height: 0.4,
          width: '100%',
          backgroundColor: '#141313',
        }}
      />
    );
  };

  render() {
    const { navigate } = this.props.navigation;

    if (this.state.isLoading) {
      return (
        <View style={{ flex: 1, paddingTop: 21 }}>
          <ActivityIndicator />
        </View>
      );
    }
    const upc = navigate.getParams('upcCode')
      console.log(upc)

    return (

      <View style={styles.viewStyle}>
        

        <SearchBar round

          searchIcon={{ size: 25 }}
          onChangeText={text => this.SearchFilterFunction(text)} onClear={text => this.SearchFilterFunction('')}
          placeholder="Type Here to Search..." value={this.state.search}

        />
        {

          this.state.search.trim() != "" ?

            <FlatList data={this.state.dataSource}
              ItemSeparatorComponent={this.ListViewItemSeparator}
              renderItem={({ item }) => (
                <View style={styles.container}>

                  <TouchableHighlight onPress={() => this.props.navigation.navigate('Summary', {
                    ProductObject: item
                  })}
                  >
                    <View >
                      {
                        this.GetFlag(item.ingredients, 'Haram') == true ?

                          <Image source={images['Haram']} style={styles.imageView} /> :

                          this.GetFlag(item.ingredients, 'Halal') == true ? 
                          <Image source={images['Halal']} style={styles.imageView} /> :
                          this.GetFlag(item.ingredients,'Doubtful') == true ?
                          <Image source={images['Doubtful']} style={styles.imageView} /> :
                          null
                      }


                      <Text style={styles.baseText}>

                        <Text style={styles.titleText}  >
                          {item.Name}{'\n'}{'\n'}

                        </Text>

                      </Text>
                    </View>
                  </TouchableHighlight>

                </View>

              )}

              enableEmptySections={true}
              style={{ marginTop: 11 }}
              keyExtractor={(item, index) => index.toString()}
            /> : <FlatList></FlatList>

        }

      </View>

    );
  }
}





export default function ScanScreen({navigation}) {
  const [hasPermission, setHasPermission] = useState(null);
  const [scanned, setScanned] = useState(false);

  useEffect(() => {
    (async () => {
      const { status } = await BarCodeScanner.requestPermissionsAsync();
      setHasPermission(status === 'granted');
    })();
  }, []);

  const handleBarCodeScanned = ({ type, data }) => {
    setScanned(true);
    
    navigation.navigate("Home",{
      upcCode: data
    })
  };
  

  if (hasPermission === null) {
    return <Text>Requesting for camera permission</Text>;
  }
  if (hasPermission === false) {
    return <Text>No access to camera</Text>;
  }

  return (
    <View
      style={{
        flex: 1,
        flexDirection: 'column',
        justifyContent: 'flex-end',
      }}>
      <BarCodeScanner
        onBarCodeScanned={scanned ? undefined : handleBarCodeScanned}
        style={StyleSheet.absoluteFillObject}
      />

      {scanned && <Button title={'Tap to Scan Again'} onPress={() => setScanned(false)} />}
    </View>
  );
}

下面是我的AppNavigator.JS代码,如果它有助于查看导航

function MainTabNavigator() {
  return (

    <Tab.Navigator tabBarOptions={{
      activeTintColor: 'red',
      inactiveTintColor: 'gray'
    }}
      screenOptions={({ route }) => ({
        tabBarIcon: ({ color, size }) => {
          let iconName;
          let tabBarVisible = true;
          if (route.name == 'Home') {
            iconName = 'md-home'
          } else if (route.name == 'Scan') {
            iconName = 'md-camera'

          } else if (route.name == 'Menu') {
            iconName = "md-menu"
          }
          else if (route.name == 'Login') {
            iconName = "md-log-in"
          }

          return <Ionicons name={iconName} color={color} size={size} />
        }
      })}
    >

      <Tab.Screen
        name='Home'
        component={HomeScreen}
        options={({route}) => ({
          title: "Search for Products",
          headerBackTitleVisible: false,

          headerStyle: {
            backgroundColor: '#1c2845',
          },
          headerTintColor: '#fff',
          headerTitleStyle: {
            fontSize:22,
            fontFamily: 'DamascusLight'
          }
        })}
         
      />
      <Tab.Screen
        name='Login'
        component={LoginScreen}
      />
      <Tab.Screen name='Scan' component={ScanScreen} />
      <Tab.Screen name='Menu' component={SearchScreen} />
    </Tab.Navigator>

  )
}


function MainStackNavigator() {

  return (

    <NavigationContainer>
      <Stack.Navigator>

        {/* <Stack.Screen name='Login' component={LoginScreen} /> */}
        <Stack.Screen name='HomeScreen' component={MainTabNavigator}
          options={({ route }) => ({
            title: 'Search for Products',
            headerBackTitleVisible: false,

            headerStyle: {
              backgroundColor: '#1c2845',
            },
            headerTintColor: '#fff',
            headerTitleStyle: {

              fontSize: 22,
              fontFamily: "DamascusLight"
            },
          }
          )} />
        <Stack.Screen name='RegistrationScreen' component={RegistrationScreen} />

        <Stack.Screen
          name="Summary"
          component={SummaryScreen}
          options={({ route }) => ({

            headerTitle: () =>
              <View style={styles.header}>
                <Text numberOfLines={1} style={styles.title}>{route.params.title}</Text>
                <Text numberOfLines={1} style={styles.subtitle}>{route.params.subtitle}</Text>
              </View>,
            headerBackTitleVisible: false,
            headerStyle: {
              backgroundColor: '#1c2845',
              height: 100
            },
            headerTintColor: '#fff',
            headerTitleStyle: {

              fontSize: 12,
              fontFamily: "DamascusLight"
            },
          }
          )}
        />
        <Stack.Screen
          name="ScanSummary"
          component={ScanSummary}
          // options={({route}) => ({
          //   headerTitle: () =>
          //  <View style={styles.header}>
          //      <Text numberOfLines={1}>{route.params.title}</Text>
          //      <Text numberOfLines={1}>{route.params.subtitle}</Text>
          //  </View>,
          //   headerStyle: {
          //     backgroundColor: '#1c2845',
          //     height: 100
          //   },
          //   headerTintColor: '#fff',
          //   headerTitleStyle: {

          //     fontSize: 12,
          //     fontFamily: "DamascusLight"
          //   },
          // })}
        />
      </Stack.Navigator>
    </NavigationContainer>

  )

}

export default MainStackNavigator

1 个答案:

答案 0 :(得分:1)

如果您使用的是反应导航5

您可以通过以下方式访问参数

this.props.route.params

如果年龄较大

this.props.navigation.state.params