gpt4 book ai didi

javascript - 在 React js 中收到错误 "this.props.sumOfPrices is not a function"?

转载 作者:行者123 更新时间:2023-12-02 21:44:24 25 4
gpt4 key购买 nike

我是 React js 新手,收到以下错误“TypeError: this.props.sumOfPrices is not a function”我使用 props 在 Course 类点击器函数中调用此函数。我的代码如下:

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;

最佳答案

您有拼写错误。这是运行代码

import React, { Component } from 'react';
import Course from './Course';

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;

关于javascript - 在 React js 中收到错误 "this.props.sumOfPrices is not a function"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60295343/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com