类型错误:this.props.function 不是一个函数

A.S*_*S.J 5 javascript reactjs

首先,我想说,我知道关于这个话题有很多问题。我通读了其中的大部分内容,并仔细检查了我的代码,但我似乎无法让它工作。

我有以下子组件,其中包含一个图像,您可以通过单击该图像来更改该图像(您可以迭代 5 个图像的数组)。

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}/>
        );
    }
}
Run Code Online (Sandbox Code Playgroud)

这是父组件:

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>
        )
    }

}
Run Code Online (Sandbox Code Playgroud)

奇怪的是,它与同一子组件内的另一个函数完美地配合。我使用了相同的结构,并且还仔细检查了是否有任何拼写错误,但没有任何帮助。

我仍然收到相同的错误消息TypeError: this.props.changeIcon is not a function。我错过了什么吗?有人能发现错误吗?

编辑: id-prop 在另一点添加。为了保持简单,我没有包括它。

Fal*_*aly 2

changeIcons不属于 props,而只是组件的一个方法

而不是这个:

<Images onChangeIcon={this.props.changeIcons}
Run Code Online (Sandbox Code Playgroud)

尝试这个:

<Images onChangeIcon={this.changeIcons}
Run Code Online (Sandbox Code Playgroud)

更新:

尝试在回调中使用箭头函数看看问题出在哪里:

return (
    <img src={imgs[pointer]} onClick={() => this.changeIcon() }/>
);
Run Code Online (Sandbox Code Playgroud)

或者将changeIcon变成箭头函数:

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}/>
    );
}
Run Code Online (Sandbox Code Playgroud)