【问题标题】:Is it possible to use a react Hook Component inside a Class?是否可以在类中使用反应钩子组件?
【发布时间】:2019-10-27 13:17:49
【问题描述】:

我想在我的应用程序中实现暗模式,我用类和组件构建了所有它,当我尝试实现 react-native-dark-mode 时,我收到一个错误,我无法在类中使用 Hook .重写所有内容将花费大量时间。

原创

import { useDarkMode } from 'react-native-dark-mode'

function Component() {
    const isDarkMode = useDarkMode()
    return <View style={{ backgroundColor: isDarkMode ? 'black' : 'white' }} />
}

但我想要类似的东西:

import { useDarkMode } from 'react-native-dark-mode'

class Home extends React.Component ... 
render() {
    const isDarkMode = useDarkMode()
    return (<View style={{ backgroundColor: isDarkMode ? 'black' : 'white' }} />)
}

【问题讨论】:

  • 您找到了除此答案之外的任何解决方法

标签: react-native react-hooks


【解决方案1】:

钩子不能直接从类组件中使用,但您可以引入一个函数组件,该组件将从钩子中提取您需要的值:

function ViewWithTheme() {
    const isDarkMode = useDarkMode()
    return <View style={{ backgroundColor: isDarkMode ? 'black' : 'white' }} />
}

class Home extends React.Component {
    // ...
    render() {
        return <ViewWithTheme />
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-11-01
    • 2021-03-16
    • 1970-01-01
    • 1970-01-01
    • 2020-09-17
    • 2020-07-06
    相关资源
    最近更新 更多