我的容器具有动态背景,用户会更改它的动态背景,因此我需要根据背景色设置文本颜色,例如,我将容器设置为黑色背景,然后为文本设置白色, 我正在为我的App使用ReactJs和材料UI库,请提出一些好的路径。
答案 0 :(得分:1)
请参阅下面的示例代码。
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);
这是更新的代码和框
检查here
答案 1 :(得分:0)
页面:
<div className="divao">
<span className="textao">UAU</span>
</div>
css:
.divao{
background: #000;
}
.textao{
color: #FFF;
mix-blend-mode: exclusion;
}
使用此代码,.textao类的颜色会自动更改。