简体   繁体   English

切换类仅选择的元素,React JS

[英]Toggle class only selected element, React JS

I am trying to toggle class in one of my react component. 我正在尝试在我的react组件之一中切换类。 At the beginning of the stage the element will be represented image and a hidden (disable) description. 在阶段的开始,元素将被表示为图像和隐藏(禁用)描述。 Whenever the user hover the element I want to add the class display only to the element hovered and not all the child components. 每当用户将鼠标悬停在元素上时,我只想将类显示仅添加到悬停的元素上,而不是所有子组件上。 In jquery usually I would have done $(this).addClass("display"), but in react I cannot figure it out. 通常在jquery中,我会完成$(this).addClass(“ display”),但在React中,我无法弄清楚。

I have seen many post and tutorial but could not find anything in regards. 我看过很多帖子和教程,但找不到任何问候。 This is my code so far: 到目前为止,这是我的代码:

Parent component 父组件

import React, {Component} from 'react';
import ProjectItem from './ProjectItem';

let projects = [
  {
    name: 'Web Development Using PHP',
    techUsed : [
      'HTML5',
      'CSS3',
      'PHP'
    ],
    link : 'sample_link',
    img : 'asset/img/movie_catalog.png'
  },
  {
    name: 'Movie Catalog',
    techUsed : [
      'HTML5',
      'CSS3',
      'ReactJS',
      'JavaSript',
      'RESTAPI'
    ],
    link : 'sample_link',
    img : 'asset/img/fma_web.png'
  },
  {
    name: 'Web Development',
    techUsed : [
      'HTML5',
      'CSS3'
    ],
    link : 'sample_link',
    img : 'asset/img/fma_web.png'
  }
];

//Projects Component
export default class Projects extends Component{
  constructor(){
    super();
    this.state = {
      proj : projects
    }
  }

  //handle mouse enter 
  handleMouseEnter = () =>{
    this.setState({
      isHovered : true
    });
  }
  //handle mouse leave
  handleMouseLeave = () =>{
    this.setState({
      isHovered : false
    });
  }

  //render the component
  render(){


    return(
      <section className="projects">
        {/*section project wrapper*/}
        <div className="p-wrapper">
          <h1 className="title">Projects</h1>
          <hr/>
          {/*projet wrapper*/}
          <ProjectItem projects = {this.state.proj} /> 
        </div>
      </section>
    );
  }
}

Child component 子组件

import React, {Component} from 'react';

//export the component
export default class ProjectItem extends Component{
    constructor(){
        super();
        this.state = {
            isHovered : false
        }
    }
    //handle mouse enter 
    handleMouseEnter = () =>{
        this.setState({
            isHovered : true
        });
    }
    //handle mouse leave
    handleMouseLeave = () =>{
        this.setState({
            isHovered : false
        });
    }
    //render the project item component
    render(){
        let display = "";
        //assign the class based on the state of display
        if(this.state.isHovered === true){
            display = "active";
        }else{
            display = "disable";
        }

        return(
            <div className="projects-wrapper">
                {
                    this.props.projects.map((project, index) =>{
                        return(
                            <div className="project-item"  key={index} onMouseEnter={this.handleMouseEnter} onMouseLeave={this.handleMouseLeave}>{/*FMA Web development*/}
                                <div className={"p-description " + display}>
                                <p>{project.name}</p>
                                <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Iure quos dolorem, ipsa eaque minima saepe fugit hic libero recusandae! Obcaecati esse odit id incidunt vitae aperiam dicta atque blanditiis sint?</p>
                                </div>
                                <div className="p-image">
                                <img src="asset/img/fma_web.png" alt="FMA Web Development"/>
                                </div>
                            </div>
                        )
                    })
                }
            </div>
        );
    }
} 

CSS CSS

/*Projects Start*/
.projects{
  width: 100%;
}

.p-wrapper{
  margin: 0 auto;
  width: 90%;
  height: 100%;
}
.projects-wrapper{
  margin-top: 2rem;
  width: 100%;
  display: flex;
  justify-content: center;
  flex-wrap: wrap;
}
.project-item{
  margin: 1rem;
  width: 30%;
  position: relative;
  box-shadow: 2px 3px 37px -5px rgba(0,0,0,0.84);
}
.p-description{
  position: absolute;
  height: 100%;
  width: 100%;
  background-color: rgba(43, 40, 40, 0.61);
  color: white;
}
.p-description p {
  margin: 1rem;
}
.p-title{
  margin: 1rem;
}
.active{
  display: block;
  transition: all 2s ease-in;
}
.disable {
  display: none;
}

Image-Illustration of the issue. 问题的图片说明。 在此处输入图片说明

I might be against the rules of the forum as I have already asked the question over here: LINK , However I have not gotten any concrete answer. 我可能已经违反了论坛的规则,因为我已经在这里提出了以下问题: LINK ,但是我还没有得到任何具体的答案。 Therefore, I am asking again. 因此,我再次询问。

The problem is that the local state of ProjectItem is applied to each project in this.props.projects.map . 问题是ProjectItem的本地状态应用于this.props.projects.map每个项目。 I would suggest instead mapping the projects in the Projects parent component instead, like this: 我建议改为映射Projects父组件中的Projects ,如下所示:

 this.state.proj.map((proj, index) => { return <ProjectItem project = {proj} /> } 

and then refactoring your ProjectItem component. 然后重构您的ProjectItem组件。 Hope this helps! 希望这可以帮助!

Let container be the class you wish toggle when hover 让容器成为您希望在悬停时切换的类

return(    
    <div className={"row" + (this.state.hover?"container":"")} onMouseEnter={this.toggleHover} onMouseLeave={this.toggleHover} style={{borderStyle:'solid',borderWidth:'0.3px',padding:'5px 0 0 0'}}>
        something
        </div>)

and create function which will change the state when mouse enter and leave 并创建将在鼠标进入和离开时更改状态的功能

toggleHover(e){
        console.log("is hovering")
        this.setState({"hover":!this.state.hover})
    }

and

constructor(props){
        super(props)

        this.state = {
            hover:false
        }
        this.toggleHover = this.toggleHover.bind(this)
    }

hope this help. 希望有帮助。 this is working on my pc let me know if you have some trouble 这正在我的电脑上工作,如果您遇到麻烦,请告诉我

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

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