簡體   English   中英

TypeError:this.props.function不是函數

[英]TypeError: this.props.function is not a function

首先,我想說的是,我知道關於這個話題有很多問題。 我通讀了其中的大部分內容,並仔細檢查了我的代碼,但似乎無法正常工作。

我有以下子組件,其中包含一個圖像,您可以通過單擊該圖像進行更改(可以迭代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}/>
        );
    }
}

這是父組件:

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

}

奇怪的是,它與同一子組件中的另一個函數完美配合。 我使用相同的結構,並且還仔細檢查了拼寫錯誤,但沒有任何幫助。

我仍然收到相同的錯誤消息TypeError: this.props.changeIcon is not a function 我想念什么嗎? 誰能發現一個錯誤?

編輯:id-prop添加在另一點。 為了簡單起見,我沒有將其包括在內。

changeIcons不屬於道具,而只是組件的一種方法

代替這個:

<Images onChangeIcon={this.props.changeIcons}

嘗試這個:

<Images onChangeIcon={this.changeIcons}

更新:

嘗試在回調中使用箭頭函數以查看問題所在:

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

或者只是將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}/>
    );
}

首先,您在構造函數中犯了錯誤。 像在子組件中一樣使用imgs和id。 像這樣做

import Images from "./images";

class Displayer extends React.Component {
    changeIcons = (word) => {
        console.log(word);
    }
    state = {
     imgs : ["img1","img2", "img3"],
     id: 0,
    }
//Here i dont know how you are getting img urls array.Please add your code accordingly
    render () {
        return (
            <div>
                <Images imgs={this.state.imgs} onChangeIcon={this.changeIcons} />
            </div>
        )
    }

}

就是這樣,現在應該可以了。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM