类组件的useTheme等效项 [英] useTheme equivalent for class component

查看:121
本文介绍了类组件的useTheme等效项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在班级组件中使用当前主题.

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

根据最新的(RN 5.x)文档,有一个

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

我发现 ThemeContext.Consumer 在RN 4.x中,但在5.x中不再可用.

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

是否可以通过其他方式为类组件获得useTheme()的效果?

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

推荐答案

这不是很优雅,但是它将为您完成工作.

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
}

这篇关于类组件的useTheme等效项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆