首先在index.js页面添加一个点击事件
查看效果,运行正常。
笔记:在组件中写事件时有一个缺点,例如,组件重新渲染时,handleclick事件函数会被重新加载,理论上会损耗资源,不过把handleclick事件写在useCallback函数中就可以避免这个问题。
引入并使用React的useCallback函数
index.js页面修改后代码
import Head from 'next/head'
import styles from '../styles/Home.module.css'
import { Footer } from '../components/Footer'
import { Main } from '../components/Main'
import { Header } from '../components/Header'
import { useCallback } from 'react'
import Link from 'next/link'
export default function Home() {
const bar =123456;
const handleclick = useCallback((e) =>{
console.log(e.target.href)
e.preventDefault();//阻止链接到下一个页面
alert(bar);
},[]);
return (
<div className={styles.container}>
<Head>
<title>Index page</title>
<link rel="icon" href="/favicon.ico" />
</Head>
<Header />
<Link href="/about" onClick={handleclick}>
链接到about页面
</Link>
<Main page="index"/>
<Footer />
</div>
)
}
查看效果,运行正常,至此,添加事件学习完成。