First of all, I would like to say that I know there are many questions regarding this topic. I read through most of them and I double and triple checked my code but I can't seem to get it to work.
I have the following child component, which contains an image, which you can change by clicking on said image (you can iterate through an array of 5 images).
export default class Images extends React.Component {
constructor(props) {
super(props);
this.changeIcon = this.changeIcon.bind(this);
this.state = {pointer: this.props.id-1, imgs: props.imgs };
}
changeIcon () {
const {length} = this.state.imgs;
const {pointer } = this.state;
const newPointer = pointer === length - 1 ? 0 : pointer+1;
this.setState({ pointer: newPointer });
this.props.onChangeIcon("I work");
}
render() {
const isclicked = this.props.clicked;
const { pointer, imgs } = this.state;
return(
<img src={imgs[pointer]} onClick={this.changeIcon}/>
);
}
}
This is the parent component:
import Images from "./images";
class Displayer extends React.Component {
constructor(props) {
super(props);
this.changeIcons = this.changeIcons.bind(this);
this.state = {
imgs = [link1, link2, link3, link4, link5]
}
}
changeIcons(word) {
console.log(word);
}
render () {
return (
<div>
<Images onChangeIcon={this.changeIcons} imgs={this.state.imgs}/>
</div>
)
}
}
The weird thing is, that it works perfectly fine with another function inside the same child component. I used the same structure and I also double-checked for any spelling mistakes, but nothing helped.
I still receive the same error message TypeError: this.props.changeIcon is not a function
. Am I missing something? Can anyone spot a mistake?
Edit: the id-prop is added at another point. In order so keep it simple I did not include that.
changeIcons
doesn't belong to props but just a method of your component
Instead of this:
<Images onChangeIcon={this.props.changeIcons}
Try this:
<Images onChangeIcon={this.changeIcons}
UPDATE:
Try to use arrow function in the callback to see where the problem is:
return (
<img src={imgs[pointer]} onClick={() => this.changeIcon() }/>
);
Or just turn changeIcon into arrow function:
changeIcon = () => {
const {length} = this.state.imgs;
const {pointer } = this.state;
const newPointer = pointer === length - 1 ? 0 : pointer+1;
this.setState({ pointer: newPointer });
this.props.onChangeIcon("I work");
}
render() {
const isclicked = this.props.clicked;
const { pointer, imgs } = this.state;
return(
<img src={imgs[pointer]} onClick={this.changeIcon}/>
);
}
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments