useTheme equivalent for class component

强颜欢笑 提交于 2020-06-01 05:13:05

问题


I would like to use the current theme in my class component.

According to the latest (RN 5.x) documentation, there is a useTheme() hook for that purposes. However, it doesn't mention any class equivalent.

I found ThemeContext.Consumer in RN 4.x but it is not available in 5.x anymore.

Is it possible to achieve the effect of useTheme() in some other way for a class component?


回答1:


This is not so elegant, but it will do the job for you.

Here is my method to access the theme inside a class component:

import React from 'react'
import { SafeAreaView, Text } from 'react-native'
import { useTheme } from '@react-navigation/native'

export default class Home extends React.Component {

    constructor(props) {
        super(props)
        this.state = {
            theme: undefined
        }
    }

    setTheme = theme => {
        this.setState({theme})
    }

    render () {

        console.log('theme', this.state.theme)

        return (
            <SafeAreaView>
                <SetTheme setTheme={this.setTheme} />
                <Text>Hello world</Text>
            </SafeAreaView>
        )
    }

}

const SetTheme = ({ setTheme }) => {
    const theme = useTheme()

    React.useEffect(() => {
        setTheme(theme)
        return () => null
    },[])

    return null
}


来源:https://stackoverflow.com/questions/61068807/usetheme-equivalent-for-class-component

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!