<div id="root"></div>
body {
margin: 0;
padding: 0;
}
.cat__img {
transition-property: left, top;
transition-duration: 0.5s, 0.5s;
transition-timing-function: ease, ease;
}
class Animal extends React.Component {
constructor(props) {
super(props);
this.state = {
src: props.src
}
console.log('constructor(props)');
}
static getDerivedStateFromProps(nextProps, prevState) {
console.log('getDerivedStateFromProps(nextProps, prevState)');
if (prevState.src !== nextProps.src) {
return { src: nextProps.src };
}
return null;
}
render() {
console.log('render()');
return <img src={this.state.src}></img>;
}
componentDidMount() {
console.log('componentDidMount()');
}
}
class Padre extends React.Component {
constructor(props) {
super(props);
const animals = [
'https://i.pinimg.com/236x/b2/cb/7d/b2cb7d5630eb5e5a60ed8f3e1d58e680--best-dog-food-best-dogs.jpg',
'https://pa1.narvii.com/5816/867e0deb7c7a4b651c37b9d6164c755d1cce6d6e_128.gif',
'https://pbs.twimg.com/profile_images/742621666027569152/m345-jkv_400x400.jpg',
'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRFxEoBS0Dlue23lz4MxyuuK0GXZwNvdueWbCLZFXwuM_xjIhhC',
'https://is5-ssl.mzstatic.com/image/thumb/Purple122/v4/e2/e5/40/e2e5408c-ea6a-042f-78a0-38fca8534133/source/256x256bb.jpg'
];
this.state = {
animals,
currentAnimalIndex: 0,
src: animals[0]
};
this.changeAnimal = this.changeAnimal.bind(this);
}
changeAnimal() {
this.setState((state) => {
const index = state.currentAnimalIndex + 1;
const src = state.animals[index];
if (!src) {
return {
currentAnimalIndex: 0,
src: state.animals[0]
};
}
return { currentAnimalIndex: index, src };
});
}
render() {
return <div>
<Animal src={this.state.src}></Animal>
<button onClick={this.changeAnimal}>Change animal</button>
</div>;
}
}
ReactDOM.render(<Padre />, document.getElementById('root'));
View Compiled
This Pen doesn't use any external CSS resources.