class 组件的 useTheme 等价物

useTheme equivalent for class component

我想在我的 class 组件中使用当前主题。

根据最新的 (RN 5.x) 文档,有一个 useTheme() 挂钩用于此目的。但是,它没有提到任何 class 等价物。

我在 RN 4.x 中找到了 ThemeContext.Consumer,但在 5.x 中不再可用。

对于 class 组件,是否可以通过其他方式实现 useTheme() 的效果?

这不是很优雅,但它会为你完成工作。

这是我在 class 组件中访问主题的方法:

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
}