简体   繁体   中英

Change Image onMouseover | ReactJs

I have an Card Component. It contains an image and text. By default, the image will be an redImage and the text are black. Onmouseover on that card, the default redimage should change to whiteimage and the text need to change into white color. I am displaying the card contents using map method. Now, i can change the color, while mouseover using css, but, i can't change the image properly. But, i can change the image on hover, if i am not using the map function by hardcoding the content directly in the component. After using map method only, i am facing the issue. Please let me know, how can I achieve that. Please find my code below.

/***App***/

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

class App extends Component {
constructor(props){
super(props);

this.state ={
Lists : [
{id:1, imgRed:require('../assets/images/red/das-red.svg'), imgWhite: require('../assets/images/white/das-whi.svg'),
Name: 'All-in-1 Dashboard',
Details:'Easily navigate the simple-to-use dashboard to track your volunteers, manage your opportunities and relationships, and gain access to advanced reporting.'},
{id:2, imgRed:require('../assets/images/red/scr-red.svg'), imgWhite: require('../assets/images/white/dig-whi.svg'),
Name: 'Screening Organizations',
Details:'Control the opportunities visible to your students by screening organizations. Invite your partnered nonprofits.' },
{id:3, imgRed:require('../assets/images/red/dig-red.svg'), imgWhite: require('../assets/images/white/pos-whi.svg'),
Name: 'Digitize Submission',
Details:'View all your student submissions to see what’s pending, approved or rejected.'},
{id:4, imgRed:require('../assets/images/red/tra-red.svg'), imgWhite: require('../assets/images/white/scr-whi.svg'),
Name: 'Tracking & Reporting',
Details:'Get up-to-date reports about how students are progressing with their commitments or requirements. Gain access to customizable analytics about individuals or groups of students.'},
{id:5, imgRed:require('../assets/images/red/pos-red.svg'), imgWhite: require('../assets/images/white/sup-whi.svg'),
Name: 'Post School-Run Events',
Details:'Get administration involved by postings school-run volunteering events directly on your private Opportunity Board..'},
{id:6, imgRed:require('../assets/images/red/sup-red.svg'), imgWhite: require('../assets/images/white/tra-whi.svg'),
Name: 'Support',
Details:'Get access to tons of resources on our FAQ or contact our team directly. We take pride in our commitment in helping you build your community.'},
],
};
}
render() {
return (
<div className="App" >
<SchDic Lists = {this.state.Lists}/>
</div>
);
}
}

export default App;

/***SchDiv***/

import React,{ Component } from 'react';
import { Card,CardMedia,CardHeader,CardContent,Typography,withStyles } from '@material-ui/core';

const Styles = {
card: {
width:'385px',
height:'241px',
padding:'0px',
margin:'15px',
cursor: 'pointer',
'&:hover': {
background: '#E8583E',
color:'white',
}
},

media: {
height: 41,
maxWidth:41,
margin:'15px',
},

name:{
padding:'1px',
margin:'15px',

},
details:{
fontSize: '14px',
padding: '0 15px',
minHeight: '25px',
align: 'left',
},
};

class SchDic extends Component {
constructor(props){
super(props);
this.state = {
value: 0,
img: require('../assets/images/red/das-red.svg'),
imgOne: require('../assets/images/red/dig-red.svg'),
imgTwo: require('../assets/images/red/pos-red.svg'),
imgThree: require('../assets/images/red/scr-red.svg'),
imgFour: require('../assets/images/red/sup-red.svg'),
imgFive: require('../assets/images/red/tra-red.svg'),

};
this.handleMouseOver = this.handleMouseOver.bind(this);
this.handleMouseOut = this.handleMouseOut.bind(this);
} 
handleChange = (event, value) => {
this.setState({ value });
};

handleMouseOver(val) {
if(val === 0){
this.setState({
img: require('../assets/images/white/das-whi.svg')
});
} else if(val === 1){
this.setState({
imgOne: require('../assets/images/white/dig-whi.svg')
});
} else if(val === 2){
this.setState({
imgTwo: require('../assets/images/white/pos-whi.svg')
});
} else if(val===3){
this.setState({
imgThree: require('../assets/images/white/scr-whi.svg')
});
} else if(val===4){
this.setState({
imgFour: require('../assets/images/white/sup-whi.svg')
});
} else {
this.setState({
imgFive: require('../assets/images/white/tra-whi.svg')
});
}
}
handleMouseOut(val) {
this.setState({
img: require('../assets/images/red/das-red.svg'),
imgOne: require('../assets/images/red/dig-red.svg'),
imgTwo: require('../assets/images/red/pos-red.svg'),
imgThree: require('../assets/images/red/scr-red.svg'),
imgFour: require('../assets/images/red/sup-red.svg'),
imgFive: require('../assets/images/red/tra-red.svg'),
});
}
render(){
const { classes }= this.props
const { Lists } = this.props;
const Post = Lists.map(List => {
return(
<div >
<Card className={classes.card} onMouseOver={() => this.handleMouseOver(List.id)} onMouseOut={this.handleMouseOut} elevation={1}>
<CardMedia
className={classes.media}
image={List.imgRed}
/>
<CardHeader className={classes.name}
titleTypographyProps={{variant:'h5' }}
title={List.Name}
/>
<CardContent className={classes.details} >
<Typography variant='Body2' color=" " component="p">
{List.Details}
</Typography>
</CardContent>
</Card>
</div>
)}
);
const divStyle = {
paddingLeft:'350px',
paddingRight:'150px',
display: 'flex',
flexWrap: 'wrap',
};
return(
<div className="coreFeatures" style={divStyle} >
{ Post }
</div>
)
}
}

export default withStyles(Styles)(SchDic);

"well i also stuck in the similar problem but i got the solution which really works just create an image folder in public folder of ur react project

now i created a tag in one of the react component as:

<img src= {process.env.PUBLIC_URL + '/image/xyz.png'} />

now i want this image to change by using mouseover listener

<img src= {process.env.PUBLIC_URL + '/image/xyz.png'} onMouseOver={() => this.changeImg()}/>

i defined the changeImg function as:

 changeLogo= () => { var a= document.querySelector('.logoA');
               a.setAttribute("src",'./images/logoB.svg')
              }

but the problem is ...(just read this post)

https://facebook.github.io/create-react-app/docs/using-the-public-folder "

Answer For My Question,

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

class App extends Component {
constructor(props){
super(props);

this.state ={
Lists : [
{id:1, imgRed:require('../assets/images/red/das-red.svg'), imgWhite: require('../assets/images/white/das-whi.svg'),
Name: 'All-in-1 Dashboard',
Details:'Easily navigate the simple-to-use dashboard to track your volunteers, manage your opportunities and relationships, and gain access to advanced reporting.'},
{id:2, imgRed:require('../assets/images/red/scr-red.svg'), imgWhite: require('../assets/images/white/dig-whi.svg'),
Name: 'Screening Organizations',
Details:'Control the opportunities visible to your students by screening organizations. Invite your partnered nonprofits.' },
{id:3, imgRed:require('../assets/images/red/dig-red.svg'), imgWhite: require('../assets/images/white/pos-whi.svg'),
Name: 'Digitize Submission',
Details:'View all your student submissions to see what’s pending, approved or rejected.'},
{id:4, imgRed:require('../assets/images/red/tra-red.svg'), imgWhite: require('../assets/images/white/scr-whi.svg'),
Name: 'Tracking & Reporting',
Details:'Get up-to-date reports about how students are progressing with their commitments or requirements. Gain access to customizable analytics about individuals or groups of students.'},
{id:5, imgRed:require('../assets/images/red/pos-red.svg'), imgWhite: require('../assets/images/white/sup-whi.svg'),
Name: 'Post School-Run Events',
Details:'Get administration involved by postings school-run volunteering events directly on your private Opportunity Board..'},
{id:6, imgRed:require('../assets/images/red/sup-red.svg'), imgWhite: require('../assets/images/white/tra-whi.svg'),
Name: 'Support',
Details:'Get access to tons of resources on our FAQ or contact our team directly. We take pride in our commitment in helping you build your community.'},
],
};
}
render() {
return (
<div className="App" >
<SchDic Lists = {this.state.Lists}/>
</div>
);
}
}

export default App;

/***SchDiv***/

    import React,{ Component } from 'react';
import { Card,CardMedia,CardHeader,CardContent,Typography,withStyles } from '@material-ui/core';

const Styles = {
    card: {
        width:'385px',
        height:'241px',
        padding:'0px',
        margin:'15px',
        cursor: 'pointer',
        '&:hover': {
            background: '#E8583E',
            color:'white',
            "& $imgOne": {
                display: 'none'
            },
            "& $imgTwo": {
                display: 'block'
            },
        },
    },
    media: {
        height: 41,
        maxWidth:41,
        margin:'15px',
        "& + $imgOne": {
            display: 'block'
        },
        "& + $imgTwo": {
            display: 'none'
        }
    },
    imgOne: {},
    imgTwo: {},
    name:{
        padding:'1px',
        margin:'15px',
    },
    details:{
        fontSize: '14px',
        padding: '0 15px',
        minHeight: '25px',
        align: 'left',
    },
};

class SchDic extends Component {
constructor(props){
super(props);
this.state = {
value: 0,

};
} 
handleChange = (event, value) => {
this.setState({ value });
};

render(){
    const { classes }= this.props
    const { Lists } = this.props;
    const Post = Lists.map(List => {
    return(
        <div >
            <Card className={classes.card} elevation={1}>
                <CardMedia
                    className={`${classes.media} ${classes.imgOne}`}
                    image={List.imgRed}
                />
                <CardMedia
                    className={`${classes.media} ${classes.imgTwo}`}
                    image={List.imgWhite}
                />
                <CardHeader className={classes.name}
                    titleTypographyProps={{variant:'h5' }}
                    title={List.Name}
                />
                <CardContent className={classes.details} >
                    <Typography variant='Body2' color=" " component="p">
                    {List.Details}
                    </Typography>
                </CardContent>
            </Card>
        </div>
    )}
);
const divStyle = {
paddingLeft:'350px',
paddingRight:'150px',
display: 'flex',
flexWrap: 'wrap',
};
return(
<div className="coreFeatures" style={divStyle} >
{ Post }
</div>
)
}
}

export default withStyles(Styles)(SchDic);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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