两个div块一个放置背景图一个放置背景色背景色的div通过postition附在背景图div上鼠标悬停使背景颜色改变背景图改变react
在React中实现这个效果,可以使用CSS-in-JS库如styled-components来定义样式,并使用useState来控制背景颜色和背景图的变化。
首先,安装styled-components库:
npm install styled-components
然后,创建一个组件,定义两个div块并使用styled-components来设置样式:
import React, { useState } from "react";
import styled from "styled-components";
const BackgroundDiv = styled.div`
background-image: url("your-background-image.jpg");
width: 500px;
height: 300px;
position: relative;
`;
const ColorDiv = styled.div`
background-color: ${props => props.backgroundColor};
width: 100%;
height: 100%;
position: absolute;
top: 0;
left: 0;
opacity: 0.5;
`;
const App = () => {
const [backgroundColor, setBackgroundColor] = useState("red");
const handleMouseEnter = () => {
setBackgroundColor("blue");
};
const handleMouseLeave = () => {
setBackgroundColor("red");
};
return (
<BackgroundDiv>
<ColorDiv
backgroundColor={backgroundColor}
onMouseEnter={handleMouseEnter}
onMouseLeave={handleMouseLeave}
/>
</BackgroundDiv>
);
};
export default App;
在上述代码中,BackgroundDiv表示放置背景图的div,使用url("your-background-image.jpg")设置背景图。ColorDiv表示放置背景色的div,通过backgroundColor属性传递背景颜色,并使用position: absolute将其附在背景图的div上。通过useState来控制背景颜色的变化,并通过onMouseEnter和onMouseLeave事件来改变背景颜色。
你需要将"your-background-image.jpg"替换为你自己的背景图路径
原文地址: https://www.cveoy.top/t/topic/iLNd 著作权归作者所有。请勿转载和采集!