Javascript React onClick事件在array.map()中

Javascript React onClick事件在array.map()中,javascript,reactjs,Javascript,Reactjs,编辑:为了更清晰,我已经包含了完整的代码 我不确定这是否可能。我试图通过道具传递onClick事件,但click事件不起作用 父组件如下所示: import React from 'react' import { getProductsById } from '../api/get' import Product from './Product' import { instanceOf } from 'prop-types' import { withCookies, Cookies } fro

编辑:为了更清晰,我已经包含了完整的代码

我不确定这是否可能。我试图通过道具传递onClick事件,但click事件不起作用

父组件如下所示:

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)
从“React”导入React
从“../api/get”导入{getProductsById}
从“./产品”导入产品
从“属性类型”导入{instanceOf}
从“react cookie”导入{withCookies,Cookies}
类Cart扩展了React.Component{
静态类型={
cookies:instanceOf(cookies)。需要
}
建造师(道具){
超级(道具)
const{cookies}=props;
此.state={
prods:cookies.get('uircartprods')| |“”,
对,,
总数:0,
}
this.expand=this.expand.bind(this)
这个.p=[];
}
componentDidMount(){
这是getCartProducts()
}
handleClick=(o)=>{
这个p.push(o.id)
const{cookies}=this.props
cookies.set('uircartprods',this.p.toString(),{path:'/',sameSite:true})
this.setState({prods:this.p})
console.log('单击')
}
getCartProducts=async()=>{
让产品=[]
如果(this.state.prods!=''){
const ts=this.state.prods.split(',')
对于(变量x=0;x{
const prod=this.handleClick(产品)}/>
产品.推送(prod)
})
}
this.setState({products:products})
}
}
展开(事件){
this.setState({collapsed:!this.state.collapsed})
}
handleCheckout(){
console.log('已单击签出')
}
render(){
返回(
你的车

您的购物车是空的

{this.state.products} 总计:{this.props.Total} 结账 {this.state.prods.length} ) } } 导出默认的cookies(购物车)
产品组成部分:

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
从“React”导入React;
类产品扩展了React.Component{
建造师(道具){
超级(道具);
此.state={
showDetails:false,
showModal:错,
购物车:[]
}
this.imgPath='./images/catalog/'
}
render(){
返回(
{this.props.product.title}
{this.props.product.artist}
产品:{this.props.Product.Product_type}

$;{this.props.product.price} 添加到购物车 ) } } 导出默认产品

如果我记录this.props.handler,我将无法定义。除了click处理程序之外,一切都正常工作,我想知道它是否与异步函数有关。我对反应还很陌生,还有一些概念我不太清楚,所以非常感谢您的帮助。

好的,我在这里看到一些问题

首先,不需要在构造函数中调用
this.handleClick=this.handleClick.bind(this)
,因为您使用的是arrow函数。箭头函数没有
this
上下文,相反,在函数中访问
this
将使用类中的父
this

其次,以状态存储组件是错误的。而是将导入的产品映射到渲染函数中

第三,处理程序的问题是
this.props.handler
实际上没有调用
handleClick
。您将注意到,在定义
handler={(product)=>this.handleClick}
中,它将函数返回给调用者,但实际上并不调用函数

试试这个

类产品扩展了React.Component{
建造师(道具){
超级(道具);
}
render(){
返回(
添加到购物车
);
}
}
导出默认产品;
从“./Product”导入产品
类Cart扩展了React.Component{
建造师(道具){
超级(道具);
}
handleClick=(o)=>{
console.log('click');
};
render(){
返回(
{importedProducts.map((产品)=>{
返回此.handleClick(产品)}/>;
})}
);
}
}
导出默认购物车;

您的
处理程序正在创建新函数,而不是传递函数。应该是
handler={this.handleClick}
你能发布完整的代码吗?似乎有丢失的零件。什么是进口产品?你打算用handleClick做什么?