reactjs - 在组合模型中将道具传递给孩子
问题描述
我正在使用组合模型 a,我有一个有很多孩子的父元素。我想知道是否可以在子元素中获取父元素的道具。现在我将相同的道具传递给所有组件(父母和孩子),但我想有更好的方法来做到这一点。
这里是父元素
const ImageTop = ({ results, children }) => {
const navigation = useNavigation();
return (
<>
<ImageBackground
style={{ height: height * 0.25, width: "100%" }}
source={imageToDisplay(results)}
>
<Pressable style={styles.blocArrow} onPress={() => navigation.goBack()}>
<Ionicons name="arrow-back-outline" size={32} color="white" />
</Pressable>
<TransparentsBar results={results} />
</ImageBackground>
<View style={{ marginLeft: 15, paddingTop: 15 }}>{children}</View>
</>
);
};
在这里,我将组件作为父组件的子组件传递:
const DetailsEvents = ({ route }) => {
const [results] = useState(route.params.item);
return (
<ScrollView showsVerticalScrollIndicator={false}>
<ImageTop results={results}>
<GenreAndTitle results={results} />
<Address results={results} />
<Date results={results} />
<CTA results={results} />
<Description results={results} />
<OrganizedBy results={results} />
</ImageTop>
</ScrollView>
);
};
如您所见,我正在向所有丑陋的组件发送相同的道具“结果”……我只想将道具发送给父母,孩子们可以访问该道具。有什么办法吗?
谢谢
解决方案
你可以使用反应上下文。这将消除关于分别向所有这些子组件发送相同道具的冗余。您将要做的是创建一个上下文,其中包含value
您希望应用程序全局使用的上下文,并使用该上下文的Provider
. 然后value
将可用于您可以访问和修改的所有子组件useContext
。