我正在尝试制作一个具有线性渐变的可重用组件,该组件可用于动态更改每个页面的主题/颜色,但是我一直遇到错误cannot read property of children undefined
。
import React from 'react';
import LinearGradient from 'react-native-linear-gradient';
export const GradientStyle = ({ theme }) => {
const { primary, primaryGradient2, primaryGradient1 } = theme;
return (
<LinearGradient
style={{ flex: 1 }}
colors={[primary, primaryGradient2, primaryGradient1]}>
{this.props.children}
</LinearGradient>
);
};
用法
import {GradientStyle} from '../../../styles/theme/GradientTheme'
const theme1 ={
primary: '#4c669f',
primaryGradient2: '#3b5998',
primaryGradient1: '#192f6a'
}
render() {
return (
<GradientStyle colors={theme1}>
.......content
</GradientStyle>
);
}
答案 0 :(得分:1)
您不能在功能组件中使用this.props
。您必须将其添加到解构参数中,如下所示:
export const GradientStyle = ({ children, theme }) => {
const { primary, primaryGradient2, primaryGradient1 } = theme;
return (
<LinearGradient
style={{ flex: 1 }}
colors={[primary, primaryGradient2, primaryGradient1]}>
{children}
</LinearGradient>
);
};
然后您可以像这样创建GradientStyle
:
import {GradientStyle} from '../../../styles/theme/GradientTheme'
const theme1 ={
primary: '#4c669f',
primaryGradient2: '#3b5998',
primaryGradient1: '#192f6a'
};
render() {
return (
<GradientStyle theme={theme1}></GradientStyle>
);
}