在作文模型中向孩子们传递道具



我使用的是组合模型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>
);
};

所以,正如你所看到的,我正在发送相同的道具";结果";所有丑陋的组件。。。我只想把道具发给家长,孩子们可以使用这些道具。有办法做到这一点吗?

谢谢

您可以使用React Context。这将消除将相同道具分别发送到所有这些子组件的冗余。您将要做的是创建一个具有您希望应用程序全局使用的value的上下文,并用该上下文的Provider包装根元素。然后value将可用于您的所有子组件,您可以使用useContext访问和修改这些子组件。

最新更新