首页 > 解决方案 > React Ionic,从通过路由组件定义的组件访问 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”

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

谢谢你。

标签: reactjsionic-frameworkreact-router-domreact-functional-componenthigh-order-component

解决方案


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

Home组件中

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

推荐阅读