Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
363 views
in Technique[技术] by (71.8m points)

react一直提示自定位的点击事件未定义?

定义了一个无状态组件

import React,{useState} from 'react';

import { Image } from 'antd';

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

import "./MenuBar.scss";

function ListItem(props)?{

 const hisorty = useHistory();

 const i = props.value;

 handleClick =?(i) => {

 console.log(i)

 };

 return (

 <div className="block" onClick={this.handleClick(i)}>

 <img src={i.url} style={{ height: '120px', width: '120px' }} />

 </div>

 )

}

export default function MenuBar(props)?{

 const numbers = props.menu;

 const listItems = numbers.map((item, index) =>

 <ListItem key={index} value={item} />

 );

 return (

 <ul>

 {listItems}

 </ul>

 );

}

编译的时候

image.png
一直提示 handleClick事件未定义 换了好几种写法都不可以

网上查了一下说 是babel支持的问题 需要改写配置文件 不知道这个地方要怎么改?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

两个问题点,题干中的报错是第一个,给handleClick赋值的时候没有使用关键字,在非严格模式下这样写问题不大,未定义的变量会在顶级作用域声明成全局变量,但是严格模式下,访问未声明的变量会报错,需要使用 const 或者 let 关键字声明

另一个问题是试图访问 this.handleClick,函数式组件的 this 并不指向组件本身,也不会访问组件的作用域:

<div className="block" onClick={() => handleClick(i)}>


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...