我正在开发React Native应用。我可以通过将每个容器组件包装成这样的东西来获得所需的结果:
<LinearGradient
style={{ flex: 1 }}
colors={[primary, primaryGradient2, primaryGradient1]}
locations={locations}
>
<ContentHere></ContentHere>
</LinearGradient>
我想做的是保持项目为DRY,而不必对每个容器级组件重复执行此操作。
我尝试制作一个组件,该组件以主题对象为基础,通过我想要的适当配置返回LinearGradient,如下所示:
<GradientTheme theme={theme}>
<MainContainer>Stuff here </MainContainer>
</ GradientTheme>
但是,此渲染完全不包含任何MainContainer元素。 GradientTheme的代码如下:
import React from 'react';
import PropTypes from 'prop-types';
import LinearGradient from 'react-native-linear-gradient';
export const GradientTheme = ({ theme }) => {
const { primary, primaryGradient2, primaryGradient1, locations } =
theme;
return (
<LinearGradient
style={{ flex: 1 }}
colors={[primary, primaryGradient2, primaryGradient1]}
locations={locations}
/>
);
};
GradientTheme.propTypes = {
theme: PropTypes.object
};
只是一些额外的信息,我也在使用React-Navigation。一个更理想的解决方案是采用一种全局方法来应用所有这些样式和主题。
感谢进阶!
答案 0 :(得分:1)
但是,此渲染完全不包含任何MainContainer元素。
您需要使用this.props.children
<LinearGradient
style={{ flex: 1 }}
colors={[primary, primaryGradient2, primaryGradient1]}
locations={locations}>
//add this:
{this.props.children}
</LinearGradient>
这是一个使用开始和结束标签传递给所有组件的道具,其中包含开始和结束标签之间的内容。
我尚不清楚您要完成的工作,但我怀疑将<GradientTheme/>
组件放置在应用程序的根目录或附近,并管理主题可以最好地为您服务处于其父组件状态或redux
本地。如果需要,here是一系列不错的教程,介绍了在react-native中一起使用redux和react-navigation。