上下文在React中总是空对象

时间:2018-11-19 19:58:39

标签: reactjs react-native

我正在尝试将主题添加到本机应用程序中,但是某种程度上它是行不通的。请帮助。
我有一个上下文:

import * as React from 'react';

export const VBContext = React.createContext({});

export default VBContext;  

然后我有一个使用的自定义提供程序:

import * as React from 'react';
import { VBContext } from './Context';

class Vbcrider extends React.Component<any, any> {
    constructor(props) {
        super(props)

        const { style } = props

        this.state = {
            style
        }
    }

    render() {
        const { children } = this.props;

        const Context = VBContext;

        return (
            <Context.Provider value={this.state.style}>
                {children}
            </Context.Provider>
        );
    }
}

export default Vbcrider;  

我还有一个HOC,应该将此上下文提供给其他组件:

import * as React from 'react';
import { VBContext } from './Context';

function withStyle(WrappedComponent) {
    return class extends React.Component<any, any> {
        render() {
            const Context = VBContext;

            return (
                <Context.Consumer>
                    {
                        () => <WrappedComponent {...this.props} />
                    }
                </Context.Consumer>
            );
        }
    };
}

export default withStyle;  

还有一个按钮,我在上面使用了HOC:

@withStyle
class Button extends React.Component<any, any> {
    style () {
        const {
            type,
            theme
        } = this.props;

        return {
            //some logic based on theme
        }
    }

    render () {
        const {
            onPress,
            children
        } = this.props;

        return (
            <TouchableOpacity style={this.style()} onPress={() => onPress}>
                {children}
            </TouchableOpacity>
        )
    }
}  

但是在按钮和HOC上下文中只是空对象。不明白为什么。任何帮助表示赞赏。

<Vbcrider style={{
        primaryBackgroundColor: '#0000FF',
        primaryBorderColor: '#0000CF',
        warningBackgroundColor: '#FFA500',
        warningBorderColor: '#FF8C00'
    }}>
        <App
            rootReducers={rootReducers}
            initialState={{}}
            Navigator={RootPageNavigator}
        />
    </Vbcrider>

1 个答案:

答案 0 :(得分:3)

尝试这种方式:

function withStyle(WrappedComponent) {
    return class extends React.Component<any, any> {
        render() {
            const Context = VBContext;

            return (
                <Context.Consumer>
                    {
                        (value) => <WrappedComponent {...this.props} theme={value} />
                    }
                </Context.Consumer>
            );
        }
    };
}