【问题标题】:useTheme equivalent for class component类组件的 useTheme 等效项
【发布时间】:2020-07-18 23:35:24
【问题描述】:

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

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

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

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

【问题讨论】:

  • 据我所知,使用 rn 的 ContextAPI 之后派生的主题

标签: react-native react-navigation react-navigation-v5


【解决方案1】:

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

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

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
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-14
    • 1970-01-01
    • 2016-01-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多