首页 > 解决方案 > 如何同时使用类和道具 javascript react native

问题描述

我正在使用const,以便我可以navigation为我的屏幕提供道具。现在,我需要实现componentDidMount(),但我必须切换到一个类来做到这一点。我怎样才能拥有它,以便我可以同时拥有navigation道具和类Component功能?

代码示例:

导航.ts

import { ParamListBase, RouteProp } from "@react-navigation/native";
import { StackNavigationProp } from '@react-navigation/stack';

export interface StackNavigationProps<
    ParamList extends ParamListBase,
    RouteName extends keyof ParamList = string
>   {
    navigation: StackNavigationProp<ParamList, RouteName>;
    route: RouteProp<ParamList, RouteName>;
    onPress: () => void;
}

export type Routes = {
    Screen1: undefined;
    Screen2: undefined;
    Screen3: undefined,
};

屏幕1.tsx

const Screen1 = ({ navigation }: StackNavigationProps<Routes, "Screen1">) => {
 ...
}

如何结合上面和下面的内容来包含navigation道具和React.Component

class Screen1 extends React.Component {

componentDidMount() {
    ...
  }
}

标签: javascripttypescriptreact-nativeclassreact-props

解决方案


如果你想拥有componentDidMount方法,你不必使用类组件,你可以在函数式编程中使用以下代码:

React.useEffect(()=>{
   //Writing code here , have behavior like componentDidMount
  
   return () => {
     //Cleaning up , it's have behavior like componentWillUnmount
   }

} , []); //If you add dependency , it's have behavior like componentDidUpdate

推荐阅读