簡體   English   中英

在 array.map() 中反應 onClick 事件

[英]React onClick event in array.map()

編輯:為了更清晰,我已經包含了完整的代碼

我不確定這是否可能。 我試圖通過道具傳遞一個 onClick 事件,但點擊事件不起作用。

父組件如下所示:

import React from 'react'
import { getProductsById } from '../api/get'
import Product from './Product'
import { instanceOf } from 'prop-types'
import { withCookies, Cookies } from 'react-cookie'

class Cart extends React.Component {
    static propTypes = {
        cookies: instanceOf(Cookies).isRequired
    }
    constructor(props) {
        super(props)
         const { cookies } = props;
            this.state = {
            prods: cookies.get('uircartprods') || '',
            collapsed: true,
            total: 0,
        }
        this.expand = this.expand.bind(this)
        this.p = [];
    }
    componentDidMount() {
        this.getCartProducts()
    }
    handleClick = (o) => {
        this.p.push(o.id)
        const { cookies } = this.props
        cookies.set('uircartprods', this.p.toString(), { path: '/' , sameSite: true})
        this.setState({prods: this.p })
        console.log('click')
    }
    getCartProducts = async () => {
        let products = []
        if (this.state.prods !== '') {
            const ts = this.state.prods.split(',')
            for (var x = 0; x < ts.length; x++) {
                var p = await getProductsById(ts[x])
                var importedProducts = JSON.parse(p)
                importedProducts.map(product => {
                    const prod = <Product key={product.id} product={product} handler={() => this.handleClick(product)} />
                    products.push(prod)
                })
            }
            this.setState({products: products})
        }
    }
    expand(event) {
        this.setState({collapsed: !this.state.collapsed})
    }
    handleCheckout() {
        console.log('checkout clicked')
    }
  render() {
    return (
            <div className={this.state.collapsed ? 'collapsed' : ''}>
                <h6>Your cart</h6>
                <p className={this.state.prods.length ? 'hidden' : ''}>Your cart is empty</p>
                {this.state.products}
                <h6>Total: {this.props.total}</h6>
                <button onClick={this.handleCheckout} className={this.state.prods.length ? '' : 'hidden' }>Checkout</button>
                <img src="./images/paypal.png" className="paypal" alt="Paypal" />
                <a className="minify" onClick={this.expand} alt="My cart"></a>
                <span className={this.state.prods.length ? 'pulse' : 'hidden'}>{this.state.prods.length}</span>
            </div>
        )
  }
}
    
export default withCookies(Cart)

產品組件:

import React from 'react';

class Product extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            showDetails: false,
            showModal: false,
            cart: []
        }
        this.imgPath = './images/catalog/'
    }
    render() {
    return (
        <div className="Product">
            <section>
                <img src={this.imgPath + this.props.product.image} />
            </section>
            <section>
                <div>
                    <h2>{this.props.product.title}</h2>
                    <h3>{this.props.product.artist}</h3>
                    <p>Product: {this.props.product.product_type}</p>
                    <h4>&#36;{this.props.product.price}</h4>
                    <button className="button" 
                    id={this.props.product.id} onClick={this.props.handler}>Add to cart</button>
                </div>
            </section>
        </div>
        )
    }
}

export default Product

如果我記錄 this.props.handler 我得到未定義。 除了點擊處理程序之外,一切都有效,我想知道它是否與異步功能有關。 我對 React 非常陌生,仍有一些我不確定的概念,因此感謝您的幫助。

好的,我在這里看到了一些問題。

首先,不需要在構造函數中調用this.handleClick = this.handleClick.bind(this) ,因為您使用的是箭頭函數。 箭頭函數沒有this上下文,相反,在函數內部訪問this將使用在類中找到的父this

其次,將組件存儲在狀態中是錯誤的。 相反,將您的importedProducts 映射到render 函數中。

第三,處理程序的問題在於this.props.handler實際上並沒有調用handleClick 您會注意到定義handler={(product) => this.handleClick}它將函數返回給調用者,但實際上並未調用該函數。

試試這個。

class Product extends React.Component {
  constructor(props) {
    super(props);
  }

  render() {
    return (
      <div>
        <button className="button" id={this.props.product.id} onClick={this.props.handler}>
          Add to cart
        </button>
      </div>
    );
  }
}

export default Product;
import Product from './Product'

class Cart extends React.Component {
  constructor(props) {
    super(props);
  }

  handleClick = (o) => {
    console.log('click');
  };

  render() {
    return (
      <div>
        {importedProducts.map((product) => {
          return <Product key={product.id} product={product} handler={() => this.handleClick(product)} />;
        })}
      </div>
    );
  }
}

export default Cart;

暫無
暫無

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

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