繁体   English   中英

从函数内部导出变量

[英]Export variable from within a function

如何从 Theme 组件导出isDark 或者是否可以从另一个文件中查询isDark而不导出它?

Toggle.js

import React, { Component, useEffect } from "react";
import { Particles as ReactParticles } from 'react-particles-js';
import usePersistentState from '../hooks/PersistentState';

const Theme = () => {
    const [isDark, setIsDark] = usePersistentState('theme', true); // default to dark mode

    useEffect(() => {
        if (isDark) {
            document.documentElement.classList.add('other');
        } else {
            document.documentElement.classList.remove('other');
        }
    });

    return (
        <div>
            <main>
                <input id="toggle" name="toggle" type="checkbox" checked={isDark} onChange={event => setIsDark(event.target.checked)} />
                <label htmlFor="toggle" className="switch" id="switch"></label>
            </main>
        </div>
    )
}

class Toggle extends Component {
    render() {
        return (
            <Theme />
        );
    }
}

export default Toggle;

我尝试使用isDarkBackground.js

import React, { Component } from 'react';
import { isDark } from './Toggle' <- doesnt work obviously
console.log(isDark)

const PARAMS = {
    "text": {
        "color": {
            "value": `${isDark ? '#000000' : '#FFFFFF'}`
        },
        ...

使用PARAMS地方:

class Background extends Component {
    render() {
        return (
            <div className="particles">
                <ReactParticles width='100vw' height="100vh" params={PARAMS} />
            </div>
        )
    }
}

使用钩子。 将其useTheme之类的东西,并让它返回读取的主题值。 您还可以考虑使用上下文,以便可以在上下文提供程序中缓存主题值。

是一个例子。 您可以看到我创建了一个上下文值,该值可以保留在以后可以通过 useTheme 注入的单个主题实例上。 您可以向上下文对象添加任何您想要的内容,并允许挂钩有选择地将这些值导出给使用者。 这很好,因为钩子可以接受一堆冗长的值和设置器,并为消费者提供更符合人体工程学的 API。 这就是 react-redux 和 react-router 的工作原理。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM