简体   繁体   English

反应无状态组件中的onMouseEnter div时如何更改图像src

[英]How to change image src when onMouseEnter div in react stateless component

I'm beginner in react.我是反应的初学者。 I want to change my image src when mouse enter the div.当鼠标进入 div 时,我想更改我的图像 src。

Here is my code.这是我的代码。

const CategoryImage = styled.img.attrs(props => ({
  src: props.url,
}))`
  width: 80px;
  height: 80px;
  margin: 5px auto;
`;

let imgUrl = ``;

const Category = ({ categoryItems }) => {
  function handleHover(category) {
    const {
      category: { hoverUrl },
    } = category;
    // console.log(hoverUrl);
    imgUrl = hoverUrl;
  }
  function handleUnHover(category) {
    const {
      category: { url },
    } = category;
    // console.log(url);
    imgUrl = url;
  }

  return (
    <Container>
      <Grid>
        {categoryItems.map(category => (
          <CategoryContainer
            key={category.id}
            onMouseEnter={() => handleHover({ category })}
            onMouseLeave={() => handleUnHover({ category })}
          >
            <CategoryImage url={imgUrl} alt={category.name} />
            <CategoryName key={category.id}> {category.name} </CategoryName>
          </CategoryContainer>
        ))}
      </Grid>
    </Container>
  );
};

Can I change image without using state?我可以在不使用状态的情况下更改图像吗?

Most of Questions usually use state to change image.大多数问题通常使用状态来改变图像。 I think state isn't needed when changes occurs in my case(codes) though.我认为当我的案例(代码)发生变化时不需要状态。

And, I heard that performance usually better without using state.而且,我听说不使用状态通常性能会更好。 Is that right?那正确吗?

Always Appreciate u guys:)永远欣赏你们:)

In case of 2 images , just add css property.如果有 2 张图片,只需添加 css 属性。 Hide it by display none , and position all the images at top ....通过 display none 隐藏它,并将所有图像放在顶部......

On mouse over or enter , in this event , pass the class name , that's it .....在鼠标悬停或输入时,在此事件中,传递类名,就是这样.....

I did this task long back, but can't remember exactly what I had done ,我很久以前做过这个任务,但不记得我做了什么,

Try this尝试这个

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM