简体   繁体   中英

React Native send params between Drawer header and specific screen using header icon

I'm starting with React Native and I would like to open an input search field on a specific screen to filter some results displayed on that screen using the right header icon (search icon).

I was able to use initialParams on Drawer.Screen and I can console.log that param on results screen when the screen loads. I just don't know how to pass this param again (as true ) when I click on header icon being on results screen already.

app.routes.tsx:

const Drawer = createDrawerNavigator();

export function AppRoutes() {

const [openFilter, setOpenFilter] = useState(false);

return(
...
<Drawer.Screen
    name="Results"
    component={Home}
    initialParams={{ openFilter: openFilter }}
    options={{
        headerRight: ({}) => (
            <BorderlessButton
                onPress={() => {
                    setOpenFilter(true);
                    console.log(openFilter);
                }}
            >
                <Feather name="search" size={24} color={theme.colors.heading} style={{ marginRight: 15 }} />
            </BorderlessButton>
        ),
    }}
/>;
}

Home.tsx:

export function Home({ route }: any) {

    const openFilter = route.params.openFilter;
    console.log(openFilter);
    const [filter, setFilter] = useState(false); // I would manage filter to be true

return(
...
    {filter &&
        <View style={{ marginBottom: 24, paddingHorizontal: 10 }}>
           <TextInput
              style={{ borderBottomColor: 'white', borderBottomWidth: 1 }}
           />
       </View>
    }
...

I think that if I'd turn openFilter into true by clicking on header icon I can display the input text. Should I re-render the results screen?

I found a method from navigation that I was using to manage navigation between screens and I can send any params with it:

const Drawer = createDrawerNavigator();

export function AppRoutes() {

const navigation: any = useNavigation();
const [openFilter, setOpenFilter] = useState(false);

return(
...
<Drawer.Screen
    name="Results"
    component={Home}
    initialParams={{ openFilter: openFilter }}
    options={{
        headerRight: ({}) => (
            <BorderlessButton
                onPress={() => {
                    navigation.setParams({ openFilter: openFilter}); // here is the method from navigation
                }}
            >
                <Feather name="search" size={24} color={theme.colors.heading} style={{ marginRight: 15 }} />
            </BorderlessButton>
        ),
    }}
/>;
}

And now I can get openFilter or any other param on Home screen.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM