reactjs - 反应按钮 onClick
问题描述
[使用 const history 后出错]
即使我遵循了互联网中提到的相同步骤,我也无法使用历史钩子。非常感谢一些帮助
import React, { Component } from 'react'
import LoginScreen from './LoginScreen'
import './MyStyles.css'
import { useHistory } from "react-router-dom"
function Home() {
const history = useHistory();
return (
<div>
<html>
<head>
<title>CSS Website Layout</title>
</head>
<body>
<div class="topnav">
<button>Home</button>        
<button>Blog</button>        
<button>Merchandise</button>          
<button>About us</button>      
<button style={{float: 'right'}} onclick={()=> history.push("/LoginScreen")}>Sign Up!</button>
</div>
我得到的错误是
Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
1. You might have mismatching versions of React and the renderer (such as React DOM)
2. You might be breaking the Rules of Hooks
3. You might have more than one copy of React in the same app
See https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem.
解决方案
首先,您使用的是 onclick 而不是 onClick。onclick 在使用 html 时可以,但在使用 react 时使用 onClick。
而不是使用内联函数,而是创建一个名为 handleClick 的单独函数,然后在单击后调用此函数。
如需更多参考,请查看此链接 - React Router Dom
推荐阅读
- python - Pandas groupby(+15 分钟运行时间)
- c - 为什么我的
将 __sig_atomic_t 定义为 int 而不是 volatile int - android - 使用 SearchView 进行搜索时出现 Android 列表视图错误
- vba - 使用指定的搜索关键字过滤表
- typescript - 具有 rxjs.Observable 属性的复杂对象
- reactjs - 如何在 FlatList 中记录其他事件?
- swift - 检索用户电子邮件以进行用户名签名 firebase
- c++ - gflags 参数提取在调试模式下不起作用(C++)
- matlab - 将单个单元格中的值转换为矩阵
- python - Tensorflow:数组activation1,它是Div运算符的输入,产生输出数组dropout/div,缺少最小/最大数据