How to call Screen / Component class method from react-navigation Header

后端 未结 5 2065
死守一世寂寞
死守一世寂寞 2021-02-09 00:27

I need to call SearchScreen class method from a React Navigation Header.

The Navigator look like this:

  Search: {
    screen: SearchScreen,
    path: \'         


        
5条回答
  •  渐次进展
    2021-02-09 01:03

    Hooks solution with FunctionComponent, useState and useEffect

    Ref the official docs (https://reactnavigation.org/docs/en/header-buttons.html#header-interaction-with-its-screen-component) it is done by:

    class HomeScreen extends React.Component {
      static navigationOptions = ({ navigation }) => {
        return {
          headerTitle: ,
          headerRight: (
            

    However I could not get this to work when working with the hooks api. My state variables were always undefined, but after I thought about how the hooks api is implemented it all made sense, so the solution was to update the navigation param every time a significant state variable was changed:

    const [count, setCount] = useState(0);
    
    useEffect(() => {
        props.navigation.setParams({ increaseCount });
    }, [count]);
    
    const increaseCount = () => setCount(count + 1);
    

提交回复
热议问题