我做了5个方块,想让鼠标悬停时每个方块上的字母都变粗,我做了isHover
状态,根据状态改变文字的粗细,但问题是5个字的粗细都变了,我觉得用条件渲染可以解决,但不知道怎么用,当然只能用css实现,但是我想用条件渲染来实现它,因为我正在简明地练习代码。
import "./styles.css";
import styled from "styled-components";
import { useState } from "react";
export default function App() {
const array = [
{ id: "1", title: "ABC" },
{ id: "2", title: "DEF" },
{ id: "3", title: "GHI" },
{ id: "4", title: "JKL" },
{ id: "5", title: "MNO" }
];
const [isHover, setIsHover] = useState(false);
return (
<Head isHover={isHover}>
<div className="header">
{array.map((content, id) => {
return (
<div
className="header__title"
onMouseEnter={() => {
setIsHover(true);
}}
onMouseLeave={() => {
setIsHover(false);
}}
>
{content.title}
</div>
);
})}
</div>
</Head>
);
}
const Head = styled.div`
position: fixed;
top: 0;
bottom: 0;
left: 0;
right: 0;
.header {
display: inline-flex;
border: 1px solid black;
box-sizing: border-box;
}
.header__title {
border: 1px solid red;
padding: 5px 10px;
font-weight: ${(props) => (props.isHover ? "700" : "400")};
}
`;
代码和框
https://codesandbox.io/s/aged-cherry-53pr2r?file=/src/App.js:0-1170
3条答案
按热度按时间prdp8dxp1#
问题是你对所有的5个块都使用了相同的状态。你可以采取多种方法来解决这个问题。
1.多国
您可以创建5个不同的
isHover<N>
状态(可能是单个状态,但作为一个数组)2.组件提取
您只需为数组中的每个条目提取一个组件,并在该组件中进行状态管理。
**3.使用
style
prop **使用
style
属性直接应用字体粗细(方法2的扩展)4.中央支助事务厅
CSS已经允许你跟踪不同元素的悬停状态,你不需要在javascript中手动跟踪。
nkcskrwz2#
这里不需要使用React状态和事件监听器,您可以在CSS中完成所有操作:
klr1opcd3#
添加这个伪类就可以了