用于 React NextJS 的映射对象 JSX 内的 onClick 不起作用

我有一个组件:


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;

但是,当我的 onClick 在映射函数内时,它并没有控制台记录任何内容。


这是我的 ImageItem 组件:


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;

我在这里做错了什么?


茅侃侃
浏览 299回答 1
1回答

森林海

您没有将点击处理程序分配给您的组件,它应该如下所示:class ImageItem extends Component {&nbsp; &nbsp; render() {&nbsp; &nbsp; &nbsp; &nbsp; return (&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <a href="#" onClick={this.props.onClick}>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <img&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; className="portfolio-image"&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; src={this.props.image}&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; alt={this.props.title}&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; />&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; </a>&nbsp; &nbsp; &nbsp; &nbsp; );&nbsp; &nbsp; }}export default ImageItem;
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript