简体   繁体   中英

onClick inside mapped object JSX for React NextJS not working

I have a component :

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

class ImageList extends Component {

    handleClick() {
        console.log('Testing testing...'); // ---> This is not working.
    }
    render() {
        const images = this.props.images.map(image => {
            return (
                <ImageItem
                    onClick={this.handleClick}
                    key={image.id}
                    image={image.src}
                    title={image.title}
                />
            );
        });

        return (
            <div className="image-list" ref={el => (this.el = el)}>
                {images}
            </div>
        );
    }
}

export default ImageList;

However, my onClick is not console logging anything out when it is inside the mapped function.

This is my ImageItem component:

import React, { Component } from 'react';

class ImageItem extends Component {
    render() {
        return (
            <a href="#">
                <img
                    className="portfolio-image"
                    src={this.props.image}
                    alt={this.props.title}
                />
            </a>
        );
    }
}

export default ImageItem;

What am I doing wrong here?

You are not assigning the click handler to your component it should look like this :

class ImageItem extends Component {
    render() {
        return (
            <a href="#" onClick={this.props.onClick}>
                <img
                    className="portfolio-image"
                    src={this.props.image}
                    alt={this.props.title}
                />
            </a>
        );
    }
}

export default ImageItem;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM