Dopiero uczę się reacta, ale kombinowałbym w tym kierunku.
Utworzenie dwóch komponentów Images i Gallery.
W Gallery, state z tablicą obiektów images, gdzie każdy z obiektów ma właściwości 'alt', 'id', 'src', i 'value' - określającą czy element jest powiększony.
funkcja handleClick przekazywana jest jako props do komponentu Image, tam dodawany jest parametr id również przekazywany w propsach. Na podstawie id funkcja handleClick zmienia value activ na disactiv konkretnego obrazka.
W metodzie render mam 2 obiekty z klasami css (aktywna i nieaktywna). W zależności czy value state konkretnego obrazka jest aktywne czy nieaktywne przekazuje odpowiednią klasę w propsach do stylu komponentu Image.
Nie wiem czy to ma sens, ale jakoś działa:
index.js
import React from 'react';
import ReactDOM from 'react-dom';
import Gallery from './Gallery';
const destination = document.querySelector("#container");
ReactDOM.render(
<Gallery />,
destination
)
Gallery.js
import React, {Component} from 'react';
import Image from './Image';
import apple from './apple.jpg';
import banana from './banana.jpg';
import strawberry from './strawberry.jpg';
class Gallery extends Component {
constructor(props) {
super(props);
this.state = {
images: [
{
alt: 'apple',
id: 0,
src: apple,
value: 'disactive'
},
{
alt: 'banana',
id: 1,
src: banana,
value: 'disactive',
},
{
alt: 'strawberry',
id: 2,
src: strawberry,
value: 'disactive',
},
]
}
this.handleClick = this.handleClick.bind(this);
}
handleClick(id) {
const newImages = [];
for(let i=0; i<this.state.images.length;i++){
if(this.state.images[i].id != id){
newImages.push(this.state.images[i]);
} else {
let changingElement = {
alt: '',
id: -1,
src: '',
value: ''
};
changingElement.alt = this.state.images[i].alt;
changingElement.id = this.state.images[i].id;
changingElement.src = this.state.images[i].src;
changingElement.value = this.state.images[i].value === 'active' ? 'disactive' : 'active';
newImages.push(changingElement);
}
}
this.setState({images: newImages});
}
render() {
const disactiveStyle = {
width: '33%'
}
const activeStyle = {
width: '50%'
}
const gallery = this.state.images.map(img => (
<div key={img.id}>
<Image id={img.id} src={img.src} alt={img.alt} style={img.value === 'active' ? activeStyle : disactiveStyle } value={img.value} changeActiv={this.handleClick}/>
</div>
));
return (
<div>
{gallery}
</div>
)
}
}
Image.js
import React, {Component} from 'react';
class Image extends Component {
render(){
return(
<img id={this.props.id} src={this.props.src} alt={this.props.alt} style={this.props.style} onClick={()=>this.props.changeActiv(this.props.id)}></img>
)
}
}
export default Image;