Javascript 如何在React应用程序的许多CSS属性中使用JS变量
我已经为提示气泡创建了一个组件。 这里是我的Javascript 如何在React应用程序的许多CSS属性中使用JS变量,javascript,html,css,reactjs,stylus,Javascript,Html,Css,Reactjs,Stylus,我已经为提示气泡创建了一个组件。 这里是我的HintBubble组件: import React from 'react'; const HintBubble = ({ text, pointerDirection = "top", color = "#f7b049" }) => { return ( <section id="hint-bubble" className={`hint-bubble-${pointerDirection}`}>
HintBubble
组件:
import React from 'react';
const HintBubble = ({ text, pointerDirection = "top", color = "#f7b049" }) => {
return (
<section id="hint-bubble" className={`hint-bubble-${pointerDirection}`}>
{text}
</section>
);
};
export default HintBubble;
import React, {createRef, useEffect} from 'react';
const HintBubble = ({text, pointerDirection = 'top', color = '#f7b049'}) => {
const hint = createRef();
useEffect(() => hint.current.style.setProperty('--hint-color', color), [
color,
]);
return (
<section
ref={hint}
id="hint-bubble"
className={`hint-bubble hint-bubble-${pointerDirection}`}
>
{text}
</section>
);
};
export default HintBubble;
要创建中显示的所有状态,我必须设置背景色
,边框底色
,边框左颜色
。。。不同类的属性
我知道我可以通过
document.queryselector('.hint bubble top').style.backgroundColor
更改background color
属性,但我想从道具中提供color
,并在所有背景色
,边框底色
,边框左颜色
,。。。属性。您可以将颜色设置为css变量,并在组件中进行更新:
import React from 'react';
const HintBubble = ({ text, pointerDirection = "top", color = "#f7b049" }) => {
return (
<section id="hint-bubble" className={`hint-bubble-${pointerDirection}`}>
{text}
</section>
);
};
export default HintBubble;
import React, {createRef, useEffect} from 'react';
const HintBubble = ({text, pointerDirection = 'top', color = '#f7b049'}) => {
const hint = createRef();
useEffect(() => hint.current.style.setProperty('--hint-color', color), [
color,
]);
return (
<section
ref={hint}
id="hint-bubble"
className={`hint-bubble hint-bubble-${pointerDirection}`}
>
{text}
</section>
);
};
export default HintBubble;