0

我想问如何从 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”

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

谢谢你。

4

1 回答 1

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

Home组件中

  const onSubmit = () => {
    // I want to access testMethod from App.tsx in here
    props.test()
  };
于 2020-08-21T23:28:58.327 回答