【问题标题】:Dynamically change config colors.js in React Native using state/context使用状态/上下文动态更改 React Native 中的配置 colors.js
【发布时间】:2021-03-01 21:23:52
【问题描述】:

我的 RN 项目中有一个简单的 Colors 文件,如下所示:

export default {
    color: '#2e66f5',
    dark1: '#232a3a',
    dark2: '#141c2b',
    white1: '#fff',
    white2: '#fff',
    aqua: '#3ecac1',
    green: '#d5d841', 
    yellow: '#f3c51e',
    red: '#ff3235'
}

在我的应用程序中到处都在使用它。

我要做的就是使用上下文/状态来动态更改颜色、dark1、dark2 等使用状态的道具。问题是我通常会导入 useContext 并做

const {activeColor} = useContext(AppContext)

export default {
    color: activeColor,
    //etc
}

并在应用程序的任何位置设置 activeColor 状态。但是由于 Colors.js 不是一个反应组件,我不能在这个文件中使用上下文/状态。

【问题讨论】:

    标签: react-native react-context


    【解决方案1】:

    React 页面展示了如何使用 useContext React Hook 的一个很好的示例: https://reactjs.org/docs/hooks-reference.html#usecontext

    ContextHolder.ts

    const colors = {
      ....
    }
    function updateContext(attr)
    {
      colors: attr,
    }
    const contextToUse = {
      colors: colors,
      updateContext: updateContext,
    }
    export default contextToUse;
    

    文件 2:

    import contextToUse from "../ContextHolder.ts";
    const context = createContext(contextToUse);
    

    然后调用updateContext

    context.updateContext({dark1: "#3A3A3A"});
    

    【讨论】:

    • 这根本不是我想做的。如果您阅读并理解了我的帖子,我正在尝试使用上下文 api 更改颜色对象的值,而不是相反!
    • 很难理解这篇文章,因为你的措辞非常混乱。请用您在评论中所说的内容重新措辞。
    • 它非常明显和清楚我需要做什么......我只是想将颜色的值:'#2e66f5',更改为颜色:'red'。 (在 colors.js 文件中)我该怎么做? (当然是动态的)
    • 更新帖子。 colordark1dark2 不是道具,因为它们不会传递到元素或组件中。它们是上下文对象的属性。在我看来,更清楚的表述方式是您想使用上下文挂钩更新上下文对象属性。
    • 这就是我想要达到的目标,我会试试这个,谢谢
    猜你喜欢
    • 2021-11-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-06
    • 1970-01-01
    • 2021-12-25
    相关资源
    最近更新 更多