如何在使用React时悬停在方框上显示按钮?

11

我正在开发一个React在线商店项目。我想让“快速查看”和“加入购物车”按钮只在悬停在它们所在的产品框上时可见。同时,它们应该是可点击的。以下是ProductBox的代码:

const ProductBox = ({ name, price, promo, stars }) => (
  <div className={styles.root}>
    <div className={styles.photo}>
      {promo && <div className={styles.sale}>{promo}</div>}
      <div className={styles.buttons}>
        <Button variant='small'>Quick View</Button>
        <Button variant='small'>
          <FontAwesomeIcon icon={faShoppingBasket}></FontAwesomeIcon> ADD TO CART
        </Button>
      </div>
    </div>
    <div className={styles.content}>
      <h5>{name}</h5>
      <div className={styles.stars}>
        {[1, 2, 3, 4, 5].map(i => (
          <a key={i} href='#'>
            {i <= stars ? (
              <FontAwesomeIcon icon={faStar}>{i} stars</FontAwesomeIcon>
            ) : (
              <FontAwesomeIcon icon={farStar}>{i} stars</FontAwesomeIcon>
            )}
          </a>
        ))}
      </div>
    </div>
    <div className={styles.line}></div>
    <div className={styles.actions}>
      <div className={styles.outlines}>
        <Button variant='outline'>
          <FontAwesomeIcon icon={faHeart}>Favorite</FontAwesomeIcon>
        </Button>
        <Button variant='outline'>
          <FontAwesomeIcon icon={faExchangeAlt}>Add to compare</FontAwesomeIcon>
        </Button>
      </div>
      <div className={styles.price}>
        <Button noHover variant='small'>
          $ {price}
        </Button>
      </div>
    </div>
  </div>
);

你能分享一下你到目前为止尝试过的实现方法吗?我没有看到任何关于悬停状态或有条件地渲染按钮的内容 - 你可以采取几种不同的方法,通常最好的做法是解释一下你已经尝试了什么,并在遇到困难时来这里寻求帮助! - katamaster818
2个回答

27

请按照以下代码进行操作:

import React, {useState} from "react";

export default function ShowButtonHover() {
    const [style, setStyle] = useState({display: 'none'});

    return (
        <div className="App">
            <h2>Hidden Button in the box. Move mouse in the box</h2>
            <div style={{border: '1px solid gray', width: 300, height: 300, padding: 10, margin: 100}}
                 onMouseEnter={e => {
                     setStyle({display: 'block'});
                 }}
                 onMouseLeave={e => {
                     setStyle({display: 'none'})
                 }}
            >
                <button style={style}>Click</button>
            </div>
        </div>
    );
}

我做了!我再做一遍,希望你现在能看到。 - present_perfect
3
我点击了箭头,但是我理解您可能看不到,因为我在这里还是新手,积分少于15分 :( 再次感谢! - present_perfect

11

编辑:创建了一个codesandbox以使其更容易 https://codesandbox.io/s/stckovw-hideshow-hs3mh

实现此功能的方法可以通过以下步骤完成:

  • 为您想要触发按钮渲染的组件(在您的情况下为ProductBox)添加 onMouseEnter onMouseLeave 处理程序。

  • 将默认按钮类设置为 display = none 属性。

  • 例如,在触发事件处理程序时将显示切换为块。

如果您正在使用无状态组件进行实现:

  • const [display,setDisplay] = useState('notdisplayed');,其中notdisplayed是具有 display = none 的默认类。

  • 在您想要隐藏/显示的组件上使用<div className = {display} > 。

  • onMouseEnter onMouseLeave 定义中调用 setDisplay


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接