[英]React fundamentals: Defining components before export or as parameters for the export function?
這可能是非常基本的。 在https://reactnative.dev/docs/intro-react 上,他們展示了末尾帶有“export default”的示例,以及“export default”之前的組件定義,例如:
import React from 'react';
import { Text, TextInput, View } from 'react-native';
const Cat = () => {
return (
<View>
<Text>I am also a cat!</Text>
</View>
);
}
const Cafe = () => {
return (
<View>
<Text>Welcome!</Text>
<Cat />
<Cat />
<Cat />
</View>
);
}
export default Cafe;
后來在閱讀https://reactnavigation.org/docs/params/時,我注意到 function 組件似乎有不同的格式,其他組件定義在大括號內,如下所示:
function HomeScreen({ navigation }) {
return (
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
<Text>Home Screen</Text>
<Button
title="Go to Details"
onPress={() => {
/* 1. Navigate to the Details route with params */
navigation.navigate('Details', {
itemId: 86,
otherParam: 'anything you want here',
});
}}
/>
</View>
);
}
我想知道后一種格式是否等同於第一個示例中的格式,並嘗試了以下方法:
import React from 'react';
import { Text, TextInput, View } from 'react-native';
export default function App() {
const Cat = () => {
return (
<View>
<Text>I am also a cat!</Text>
</View>
);
}
const Cafe = () => {
return (
<View>
<Text>Welcome!</Text>
<Cat />
<Cat />
<Cat />
</View>
);
}
return(<Cafe/>);
}
實際上,測試預覽的結果與@ https://snack.expo.io/的結果相同。 將最后一次返回改為return(<View><Cat/> <Cafe/> </View>);
,或更改名稱以export default function testApp() {
也可以。 雖然兩者都有效,但我不知道這兩種格式有什么區別/優勢,並想了解更多。
常規function
與胖箭頭函數( () => {}
)不同,因為它們沒有自己的this
上下文。 您提到了這兩種類型的函數,我想明確一點,它與符號的導出方式無關。
至於導出,無論您是立即使用export default () => {}
導出符號還是先為本地 scope 定義它然后再導出,這並不重要,因為在 React 組件的情況下,您通常不'不要重用文件中的默認導出符號。 我通常將 go 用於后者,因為它使 function 定義行更短,因此允許更多的 arguments 放在一行上而無需換行。
您可以將組件導出為default
導出,也可以作為命名導出:
export const SomeComponent = () => {};
export default SomeComponent;
這樣,您將有更多方法來導入SomeComponent
// default import
import SomeComponent from './SomeComponent';
// named import
import { SomeComponent } from './SomeComponent';
也就是說,如果您的文件具有某種“根”組件。 在某些情況下,單個文件包含多個組件,這些組件都位於一個“重要性”級別。 在這種情況下,您通常根本沒有默認導出:
export const ComponentA = () => {};
export const ComponentB = () => {};
export const ComponentC = () => {};
export const ComponentD = () => {};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.