如何使用reactJs根据背景颜色更改字体颜色

IT技术 reactjs material-ui
2021-05-21 00:08:54

我有我的容器的动态背景,它会被用户改变,所以我需要根据背景颜色设置文本颜色,例如,我设置容器的黑色背景,然后我需要为文本设置白色,我正在使用 ReactJs 和材料 UI 库对于我的应用程序,请提出一些好的路径。

2个回答

请参阅下面的示例代码。

import React, { useState, useEffect } from "react";
import ReactDOM from "react-dom";
import DynamicContainer from "./style";

import "./styles.css";

function App() {
  const [bgColor, setBGColor] = useState("#422DAD");
  const [textColor, setTextColor] = useState("rgb(99,99,100)");

  function hexToRgb(hex) {
    // Expand shorthand form (e.g. "03F") to full form (e.g. "0033FF")
    var shorthandRegex = /^#?([a-f\d])([a-f\d])([a-f\d])$/i;
    hex = hex.replace(shorthandRegex, function(m, r, g, b) {
      return r + r + g + g + b + b;
    });

    var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
    return result
      ? {
          r: parseInt(result[1], 16),
          g: parseInt(result[2], 16),
          b: parseInt(result[3], 16)
        }
      : null;
  }

  useEffect(() => {
    let { r, g, b } = hexToRgb(bgColor);
    let targetColor = `rgb(${r},${g},${b})`;
    var colors = targetColor.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);
    var brightness = 1;

    var R = colors[1];
    var G = colors[2];
    var B = colors[3];

    var ir = Math.floor((255 - R) * brightness);
    var ig = Math.floor((255 - G) * brightness);
    var ib = Math.floor((255 - B) * brightness);
    setTextColor(`rgb(${ir}, ${ig}, ${ib})`);
  }, [bgColor]);

  const handleBgChange = e => {
    setBGColor(e.target.value);
  };

  return (
    <>
      <DynamicContainer bgColor={bgColor} textColor={textColor}>
        Hello World!
      </DynamicContainer>
      <p>Choose Background color</p>
      <input type="color" value={bgColor} onChange={handleBgChange} />
    </>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

这是更新的代码和框

在这里检查

页:

<div className="divao">
   <span className="textao">UAU</span>
</div>

css:

.divao{
   background: #000;
}
.textao{
   color: #FFF;
   mix-blend-mode: exclusion;
}

使用此代码,.textao 类的颜色会自动更改。