首页 > 解决方案 > 在反应 js 中出现“this.props.sumOfPrices 不是函数”的错误?

问题描述

我是 react js 的新手,我收到以下错误“ TypeError:this.props.sumOfPrices 不是函数”我正在使用道具在课程类点击器函数中调用此函数。我的代码如下:

import React, { Component } from 'react';

class CourseSles extends Component {
    sumOfPrices(price){
        this.setState({total:this.state.total + price});
    }
    constructor(props) {
        super(props);
        this.state = { total:0 };
        this.sumOfPrices=this.sumOfPrices.bind(this);
    }

    render() 
    { 
        var courses=this.props.items.map(
        (item,i)=>{
         return <Course name={item.name} price={item.price} key={i} sumofPrices={this.sumOfPrices} active={item.active}/>
        });
        return(
        <div> 
          <h1>You Can Buy Courses:</h1>
          <div id="courses">
              {courses}
        <p id="total">Toatal: <b>{this.state.total}</b></p>
          </div>
        </div> 
        );
    }
}

class Course extends Component {
    clicker(){
      var active= !this.state.active;
      this.setState({active:active});
      this.props.sumOfPrices(active ? this.props.price : -this.props.price);
    }
    constructor(props) { 
        super(props);
        this.state = { active:false };
        this.clicker=this.clicker.bind(this);
    }
    render() { 
        return ( <div>
            <p onClick={this.clicker}>{this.props.name} <b>{this.props.price}</b></p>
        </div> );
    }
}

export default CourseSles;

标签: javascriptreactjsreact-native

解决方案


更改 sumOfPrices 方法,例如:

class CourseSles extends Component {
    sumOfPrices  = (price) => {
        this.setState({total:this.state.total + price});
    }
//Rest of Code
}

推荐阅读