【问题标题】:How to use classes and props at the same time javascript react native如何同时使用类和道具 javascript react native
【发布时间】:2021-05-05 17:08:12
【问题描述】:

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

代码示例:

Navigation.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,
};

Screen1.tsx

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

如何将上面和下面的内容结合起来以包含navigation props 和React.Component

class Screen1 extends React.Component {

componentDidMount() {
    ...
  }
}

【问题讨论】:

标签: javascript typescript react-native class react-props


【解决方案1】:

如果你想有 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-05-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-29
    • 1970-01-01
    • 2019-03-24
    • 1970-01-01
    相关资源
    最近更新 更多