具有反应本征线性梯度的可重用组件

时间:2019-06-06 19:58:33

标签: react-native linear-gradients

我正在尝试制作一个具有线性渐变的可重用组件,该组件可用于动态更改每个页面的主题/颜色,但是我一直遇到错误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>


        );
    }

1 个答案:

答案 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>
    );
}