我有这种从对象数组渲染的卡片。
父组件:
[{foo: 'bar', baz: [{ name: string, path: string: '/'}]
state = {isHovering: false}
handleMouseHover = () => {
const { isHovering } = this.state;
this.setState({ isHovering: !isHovering });
}
;
我正在传递handleMouseHover()
and isHovering
作为子组件的道具。
结果是这样的:
子组件
<LinkContainer
onMouseEnter={handleMouseHover}
onMouseLeave={handleMouseHover}
className="linkContainer"
>
{isHovering && (
<FontAwesomeIcon
icon="copy"
className="copyIcon"
onClick={copyToClipboard}
/>
)}
结果是 4 张卡片,其中包含 3 个链接。每次我将鼠标悬停在链接上时,我都希望显示“复制到剪贴板”图标。然而,当我将鼠标悬停在它设置的任何项目上时isHovering
to true
从而使所有图标可见。理想情况下,我只希望我将鼠标悬停在其上的链接的图标可见。有人可以帮助我找出更好的解决方案或改进我已经编写的代码吗?
非常感激!
您可以将对象保留在您的状态中,而不是布尔值,该对象有一个键,指示以该特定键作为索引的对象是否悬停。
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>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)