Const 与类函数是 React Native

csb*_*b00 9 react-native

我最近一直在看一些关于 RN 的教程,我注意到其中一些在创建组件时不使用 class,而是使用 const。下面的代码显示了该特定教程的应用程序的主屏幕。我的问题是:他们这样做有什么原因而不是使用课堂吗?还有,有关系吗?你有什么特别的理由会使用 const 而不是 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;
Run Code Online (Sandbox Code Playgroud)

小智 9

如果不使用状态,则应使用称为无状态函数的 const。这是关于性能的。如果使用状态,则必须使用类。(react 的早​​期版本)如果升级 react-native 并使用 hooks,它会有所不同。

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


ana*_*912 6

您发布的示例是一个stateless function component. 它只是一个arrow function被分配给变量的 JavaScript const HomeScreen =。你也可以把它写成一个标准的匿名函数:

// the props you give to <HomeScreen/> get passed as parameter to the function
// by React. You can destructure them right in place, like with ({navigation}).

const HomeScreen = function({ navigation }) {
   ...
   return (...)
}
Run Code Online (Sandbox Code Playgroud)

无状态功能组件没有状态。如果您不需要状态和生命周期方法等,可以使用它们。此外,它们可以通过使用钩子转换为 stateFUL 功能组件。

钩子是预定义的函数,可以在函数组件中使用,以通过状态、生命周期管理等来增强它。但这是一个更广泛的主题。

没有钩子,你可以使用无状态组件而不是类组件来保持你的代码小(函数而不是类,没有这个,没有渲染函数,只是返回,通过导入函数并在组件内部使用它更容易地重用代码)

为了提高性能,您需要再次使用钩子(例如 useMemo() 钩子)。习惯钩子的概念需要一些时间,但这是值得的。我现在更喜欢它们而不是类组件,主要是因为代码更清晰。