反应导航v5。 StackScreen标头和StackScreen组件数据流

时间:2020-04-12 17:35:07

标签: javascript reactjs react-native react-redux react-navigation

我的React Native应用程序在Stack.Screen标头(React Navigation v5)中具有Searchbar组件,其中包含需要ProductsList组件中的数据的逻辑。有没有一种方法可以将数据从堆栈屏幕标头传递到组件,反之亦然?

这是我的StackNavigator

<Stack.Navigator>
      <Stack.Screen
        name="My App Name"
        component={Dashboard}
      />
      <Stack.Screen
        name="Products"
        component={ProductsScreen}
        options={{headerRight: (props) => <Searchbar {...props} />}}
      />
</Stack.Navigator>

具有过滤逻辑的搜索栏

const Searchbar = () => {
  const [search, setSearch] = useState('');
  const [dataSource, setDataSource] = useState('');

  const searchFilterFunction = (text) => {
    const newData = props.items.filter((item) => {
      const itemData = item.name ? item.name.toUpperCase() : ''.toUpperCase();
      const textData = text.toUpperCase();
      return itemData.indexOf(textData) > -1;
    });

    setSearch(text);
    setDataSource(newData);
  };

  return (
    <View>
      <SearchBar
        onChangeText={(text) => searchFilterFunction(text)}
        onClear={(text) => searchFilterFunction('')}
        placeholder="Type Here..."
        value={search}
        platform="android"
        cancelIcon={false}
        placeholder="Search..."
      />
    </View>
  );
};

和组件

const ProductsList = (props) => {
  return (
    <View>
      <FlatList
        data={props.dataSource}
        keyExtractor={(item) => item.id.toString()}
        renderItem={({item}) => (
          <TouchableOpacity
            style={styles.listItem}
            keyExtractor={item.id}
            onPress={() =>
              props.navigation.navigate('Detailed Info', {
                name: item.name,
                latinName: item.latinName,
                latinNameSynonyms: item.latinNameSynonyms,
                images: item.images,
                description: item.description,
              })
            }>
            <Image style={styles.image} source={{uri: item.images[0].thumb}} />
            <Text style={styles.text}>{item.name}</Text>
          </TouchableOpacity>
        )}
      />
    </View>
  );
};

如果我将Searchbar放入ProductsList函数中,但一切正常,但我需要将Searchbar内置到标题中,而我在文档中找不到任何可能的解决方案

0 个答案:

没有答案