通常,功能组件会将props
对象作为 agrument。 props
可能有任意数量的键值对。例如,您可能有props.navigation
. 但是写作function HomeScreen( navigation )
不等于写作function HomeScreen({ navigation })
。写入{ navigation }
而不是props
在参数中描述来自其父对象的值。如果你想避免解构,你可以这样写:
function HomeScreen( props ) {
return (
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
<Text>Home Screen</Text>
<Button
title="Go to Details"
onPress={() => props.navigation.navigate('Details')}
/>
</View>
);
}
同样,react 功能组件期望接收 props 对象作为参数。我们通常称它为props
,但它可以被称为任何东西。下一个块是相同的,我们只是在命名props
其他东西:
function HomeScreen( swissArmyKnife ) {
return (
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
<Text>Home Screen</Text>
<Button
title="Go to Details"
onPress={() => swissArmyKnife .navigation.navigate('Details')}
/>
</View>
);
}
对于一个参数,你是对的,可能没有必要解构。它只是一个简写。但是,当您有一个props
具有许多参数的对象,并且您只想从中提取某些值时,它就更有意义了。比如说你的props
对象有参数navigation
, trains
, busses
, airplanes
, bikes
, skateboards
,你只想在你的组件中使用一些:
function HomeScreen( {busses, bikes} ) {
// do some stuff here with busses and bikes, don't worry about the whole props object
}