gpt4 book ai didi

reactjs - react 钩悬停效果

转载 作者:行者123 更新时间:2023-12-04 16:40:41 25 4
gpt4 key购买 nike

我正在尝试使用 react 钩子(Hook)制作悬停效果
我根据一些教程编写了悬停函数

function useHover() {
const [hovered, setHovered] = useState(false);

const ref = useRef(null);

const handleMouseOver = () => setHovered(true);
const handleMouseOut = () => setHovered(false);

useEffect(() => {
const node = ref.current;
if (node) {
node.addEventListener("mouseover", handleMouseOver);
node.addEventListener("mouseout", handleMouseOut);

return () => {
node.removeEventListener("mouseover", handleMouseOver);
node.removeEventListener("mouseout", handleMouseOut);
};
}
}, [ref]);

return [ref, hovered];
}


但如何让它在我的应用程序功能中工作
export default function App() {
const [ref, isHovered] = useHover();

const reactionItems = myObject.map(([key, value]) => (
<li key={key} ref={ref}>
{isHovered ? `${key} ${value.length > 1 ? "x " + value.length : ""}` : `${key} ${value.length > 1 ? "x " + value.length : ""} ${value}`}
</li>
));


return (
<div className="App">
<h1>{string}</h1>
<h2>Reactions</h2>
<ul>{reactionItems}</ul>
</div>
);

}

我只能在 false 状态下看到它,所以第二个选项没有悬停效果

最佳答案

使用 React's events' system , 而不是 DOM 的。此外,每个项目都应该有自己的事件处理程序和状态。

创建一个返回悬停状态的钩子(Hook),以及项目的事件监听器。创建一个 Item 组件,并在其定义中使用钩子(Hook)。渲染项目。

const { useState, useMemo } = React;

const useHover = () => {
const [hovered, setHovered] = useState();

const eventHandlers = useMemo(() => ({
onMouseOver() { setHovered(true); },
onMouseOut() { setHovered(false); }
}), []);

return [hovered, eventHandlers];
}

const Item = ({ children }) => {
const [hovered, eventHandlers] = useHover();

return (
<li {...eventHandlers}>Item: {hovered && children}</li>
);
};

const myObject = {
a: 'A1',
b: 'B2',
c: 'C3',
}

function App() {
const reactionItems = Object.entries(myObject)
.map(([key, value]) => (
<Item key={key}>{value}</Item>
));

return (
<div className="App">
<h2>Reactions</h2>
<ul>{reactionItems}</ul>
</div>
);
}

ReactDOM.render(<App />, root);
<script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>

<div id="root"></div>

关于reactjs - react 钩悬停效果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61562660/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com