[英]reactjs - Render single icon on hover for list item rendered from array
I have this sort of cards that are rendered from an array of objects.我有这种从对象数组呈现的卡片。
Parent Component:父组件:
[{foo: 'bar', baz: [{ name: string, path: string: '/'}]
state = {isHovering: false}
handleMouseHover = () => {
const { isHovering } = this.state;
this.setState({ isHovering: !isHovering });
}
; ;
I'm passing down handleMouseHover()
and isHovering
down as props to a child component.我将handleMouseHover()
和isHovering
作为道具传递给子组件。
Resulting in something like this:结果是这样的:
Child Component子组件
<LinkContainer
onMouseEnter={handleMouseHover}
onMouseLeave={handleMouseHover}
className="linkContainer"
>
{isHovering && (
<FontAwesomeIcon
icon="copy"
className="copyIcon"
onClick={copyToClipboard}
/>
)}
The result is 4 cards that contain 3 links.结果是包含 3 个链接的 4 张卡片。 Each time I hover over a link I want the copy to clipboard icon to show.每次我将鼠标悬停在链接上时,我都希望显示复制到剪贴板图标。 However, at the moment when I hover over any item it sets isHovering
to true
thus making all the icons visible.但是,当我将鼠标悬停在任何项目上时,它isHovering
设置为true
从而使所有图标都可见。 Ideally I just want the the icon for the link I hover over to become visible.理想情况下,我只希望我悬停在其上的链接图标变得可见。 Can someone help me to figure out a better solution or a refinement of my already written code.有人可以帮助我找出更好的解决方案或改进我已经编写的代码。
Much appreciated!非常感激!
You could keep an object in your state instead of a boolean, that has a key indicating if the object with that particular key as index is hovered or not.您可以将一个对象保持在您的状态而不是布尔值,它有一个键,指示以该特定键作为索引的对象是否悬停。
Example例子
class App extends React.Component { state = { arr: [{ text: "foo" }, { text: "bar" }], isHovered: {} }; handleMouseEnter = index => { this.setState(prevState => { return { isHovered: { ...prevState.isHovered, [index]: true } }; }); }; handleMouseLeave = index => { this.setState(prevState => { return { isHovered: { ...prevState.isHovered, [index]: false } }; }); }; render() { const { arr, isHovered } = this.state; return ( <div> {arr.map((el, index) => ( <Child onMouseEnter={() => this.handleMouseEnter(index)} onMouseLeave={() => this.handleMouseLeave(index)} text={el.text} isHovering={isHovered[index]} key={index} /> ))} </div> ); } } function Child({ onMouseEnter, onMouseLeave, text, isHovering }) { return ( <div onMouseEnter={onMouseEnter} onMouseLeave={onMouseLeave}> {text} {isHovering && " (hovering!)"} </div> ); } ReactDOM.render(<App />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script> <div id="root"></div>
Create a property isHovered on item of an array dynamically and onMouseHover pass the item which you get in .map, now toggle the isHovered property.在数组的项目上动态创建一个属性 isHovered 并 onMouseHover 传递您在 .map 中获得的项目,现在切换 isHovered 属性。 Should work now.现在应该工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.