Const 与类函数是 React Native [英] Const vs Class Functions is React Native

查看:24
本文介绍了Const 与类函数是 React Native的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最近我一直在看一些关于 RN 的教程,我注意到其中一些在创建组件时不使用类,而是使用 const.下面的代码显示了该特定教程的应用程序的主屏幕.我的问题是:他们这样做有什么原因而不是使用课堂吗?还有,有关系吗?你有什么特别的理由要使用 const 而不是 class 吗?

I have been watching a few tutorials recently on RN and I have noticed a few of them do not use class when creating a component, instead, they are using const. The code below shows the homescreen for the app for that particular tutorial. My question is: is there a reason they are doing it this way and not using class? Also, does it matter? Is there a particular reason you would use const instead of class?

const HomeScreen = ({ navigation }) => {
    return (
      <View>
        <Text style={styles.textStyle}>This is the Home Screen</Text>
        <Button title="Go to Components Demo"
          onPress={() => navigation.navigate('Components')}
        />
        <Button title="Go to list demo"
          onPress={() => navigation.navigate('List')}
        />
        <Button title="Go to Image Screen"
        onPress={() => navigation.navigate('Image')}
        ></Button>
        <Button title="Go to Counter"
        onPress={() => navigation.navigate('Counter')}
        ></Button>
        <Button title="Colors"
        onPress={() => navigation.navigate('Color')}
        ></Button>
        <Button title="Squares"
        onPress={() => navigation.navigate('Square')}
        ></Button>
      </View>
    );
  };


const styles = StyleSheet.create({
  textStyle: {
    fontSize: 30,
    textAlign: "center"
  },
});

export default HomeScreen;

推荐答案

如果你不使用状态,你应该使用称为无状态函数的const.这是关于性能的.如果使用状态,则必须使用类.(较早版本的react)如果升级react-native 并使用hook,就会有所不同.

if you don't use state, you should use const which is called stateless function. it's about performance. if you use state, you have to use class. (earlier versions of react) if you upgrade react-native and use hooks, it will be different.

我认为你应该查看这篇文章关于类与无状态函数.

i think you should check this article about class vs stateless function.

这篇关于Const 与类函数是 React Native的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆