反应离子,通过路由组件定义的组件访问App.tsx方法

问题描述

我想问一下如何从Home.tsx访问App.tsx中定义的方法“ testMethod”

这是App.tsx(此组件的方法名为“ testMethod”)

import React from 'react';
import { IonApp,IonRouterOutlet } from '@ionic/react';
import { IonReactRouter } from '@ionic/react-router';
import { Route } from 'react-router-dom';
import Home from './pages/Home';

const App: React.FC = () => {
  const testMethod = () => {
    console.log('test');
  };
  return (
    <IonApp>
      <IonReactRouter>
        <IonRouterOutlet>
          <Route path="/home" component={Home} exact />
        </IonRouterOutlet>
      </IonReactRouter>
    </IonApp>
  );
};

export default App;

这是Home.tsx

import { IonContent,IonPage,IonSplitPane,IonButton } from '@ionic/react';
import React from 'react';
import { RouteComponentProps } from 'react-router-dom';

interface ChildComponentProps extends RouteComponentProps<any> {}

const Home: React.FC<ChildComponentProps> = (props) => {
  const onSubmit = () => {
    // I want to access testMethod from App.tsx in here
  };
  return (
    <IonContent>
      <IonSplitPane contentId="main">
        <IonPage id="main">
          <IonButton
            expand="block"
            type="submit"
            class="ion-no-margin"
            onClick={onSubmit}
          >
            Test
          </IonButton>
        </IonPage>
      </IonSplitPane>
    </IonContent>
  );
};

export default Home;

从Home.tsx中,我要执行用户单击Home.tsx中的按钮时在App.tsx中定义的方法“ testMethod”

我仍然不知道如何实现这一目标,非常感谢您的帮助。

谢谢。

解决方法

<Route path="/home" exact>
   <Home test={testMethod} />
</Route>

Home组件中

  const onSubmit = () => {
    // I want to access testMethod from App.tsx in here
    props.test()
  };