猿问

无法从 React 中的子组件调用父组件函数

我刚开始反应(本周开始)。我有一个父组件和子组件,我想在子组件中调用父方法。我已经搜索过 stackoverflow,我的代码与我得到的所有解决方案相同。


我有一个显示产品列表的父组件 ProductDisplay:


import React, { Component } from 'react';

import data from '../data'

import Product from '../Product/product.component'


class ProductDisplay extends Component {


    constructor(props) {

        super(props)

        this.state = {

            pdts: data,

        }

    }


    addToCart = () => {

        console.log('add to cart');

    }


    render() {

        return (            

                this.state.pdts.map(product => (

                <Product

                    key={product.id}

                    product={product}

                    addToCart={this.addToCart}

                />

            ))

        );

    }

}

export default ProductDisplay;

子组件是 Product ,它呈现每个产品


import React, { Component } from 'react';

import { withRouter } from 'react-router-dom';

import "./product.css";

class Product extends Component {

    constructor(props) {

        super(props);

    }


    handleClick = () => {

        this.props.addToCart();

        console.log('click');

    }


    render() {

        const product = this.props.product;

        console.log(this.props.addToCart);

        return (

            <div className="product">

                <img className="image" src={product.imgPath} alt={product.name} />

                <p className="name">{product.name}</p>

                <p className="price">Price: ₹{product.price}</p>

                <p className="category">Category: {product.category}</p>

                <button className="add">Add To Cart <i className="fa fa-cart-plus" 

                        onClick={this.handleClick}></i></button>

            </div>

        );

    }

}

export default withRouter(Product);

我想在单击按钮时从 Product 调用 ProductDisplay 的 addToCart 函数,但它不起作用。子组件本身的 handleClick 函数没有被调用。因此,从 handleClick 调用的父函数也没有被调用。


我也不确定我所做的是否可以将方法绑定到所有按钮。请帮忙


心有法竹
浏览 331回答 2
2回答

鸿蒙传说

您已将onClick侦听器放在<i>标签上,而不是放在实际的 上button,这就是为什么当您单击button.试试这个:<button&nbsp;&nbsp; &nbsp; className="add"&nbsp;&nbsp; &nbsp; onClick={this.handleClick}>&nbsp; &nbsp; Add To Cart <i className="fa fa-cart-plus"></i></button>

jeck猫

您需要将 addCart 方法与类的“this”绑定。正如 Chistopher 的回答,你的 onClick 是在 i 而不是在按钮上。要么路过。&nbsp; &nbsp;<Product&nbsp; &nbsp; &nbsp; &nbsp;key={product.id}&nbsp; &nbsp; &nbsp; &nbsp;product={product}&nbsp; &nbsp; &nbsp; &nbsp;addToCart={this.addToCart}&nbsp; &nbsp;/>或者在状态this.addToCart = this.addToCart.bind(this);
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答