【问题标题】:How to read the background color and calculate a contrast front color in a React function component?如何在 React 函数组件中读取背景颜色并计算对比正面颜色?
【发布时间】:2020-09-14 15:13:22
【问题描述】:

我正在尝试从 React 函数组件(导航标题)中读取背景颜色。

问题是我网站的一个元素会根据事件更改背景颜色。发生这种情况时,字体文本可能变得不可读(对比度不足)。

我的部分问题可能在链接线程中得到解决,但我不知道如何读取状态。我有一个函数的 SCSS 导入,但背景是全局定义的。

当我这样做时:字体颜色和背景颜色之间是否存在理想的对比?

How to change font color based on background color using reactJs

【问题讨论】:

    标签: css reactjs sass


    【解决方案1】:

    我不知道您现在如何更改背景颜色,它是否仅限于一些预定义的颜色,但如果它是预定义的,我会在 CSS 中创建颜色主题类并将正确的主题分配给根或页面的正文必须更改时。然后通过使用 CSS 特异性,我将通过网站覆盖文本颜色。

    .darkGrayTheme {
       background-color: #5d5b5b;
    }
    
     .lightGrayTheme {
       background-color: #ccc;
    }
    
     // in other CSS file
     .darkGrayTheme .myCustomWidget {
       color: #FFF;
     }
    
     .lightGrayTheme .myCustomWidget {
       color: #ddd;
     }
    

    如果背景颜色可以是任何颜色,我将通过创建颜色主题映射到可以共享通用文本颜色的颜色范围组来对所有可能的颜色进行分组,然后在整个应用程序中遵循上述 CSS 颜色主题。

    更多关于color theme creation的信息


    根据评论更新:

    如果它是预定义的并将用作道具,我建议将主题设置为顶级组件的上下文,并能够访问任何子组件中的主题对象。

    来自React hook documentation的示例

    const themes = {
      light: {
        foreground: "#000000",
        background: "#eeeeee"
      },
      dark: {
        foreground: "#ffffff",
        background: "#222222"
      }
    };
    
    const ThemeContext = React.createContext(themes.light);
    
    function App() {
      return (
        <ThemeContext.Provider value={themes.dark}>
          <Toolbar />
        </ThemeContext.Provider>
      );
    }
    
    function Toolbar(props) {
      return (
        <div>
          <ThemedButton />
        </div>
      );
    }
    
    function ThemedButton() {
      const theme = useContext(ThemeContext);
      return (
        <button style={{ background: theme.background, color: theme.foreground }}>
          I am styled by theme context!
        </button>
      );
    }
    

    【讨论】:

    • 它是预定义的,看来我必须通过道具来做到这一点。我以为你可以通过 DOM 读取当前的背景颜色。
    • @wishi 我更新了答案,我相信它会回答你的问题。
    猜你喜欢
    • 1970-01-01
    • 2013-05-26
    • 1970-01-01
    • 2020-04-04
    • 1970-01-01
    • 2019-11-10
    • 2020-05-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多