首页 > 解决方案 > 反应按钮 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> &ensp;&ensp;&ensp;&ensp;&ensp;&ensp;&ensp;
                            <button>Blog</button> &ensp;&ensp;&ensp;&ensp;&ensp;&ensp;&ensp;
                            <button>Merchandise</button> &ensp;&ensp;&ensp;&ensp;&ensp;&ensp;&ensp;&ensp;&ensp;
                            <button>About us</button>&ensp;&ensp;&ensp;&ensp;&ensp;&ensp;
                            <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.

标签: reactjsreact-hooksreact-router

解决方案


首先,您使用的是 onclick 而不是 onClick。onclick 在使用 html 时可以,但在使用 react 时使用 onClick。

而不是使用内联函数,而是创建一个名为 handleClick 的单独函数,然后在单击后调用此函数。

如需更多参考,请查看此链接 - React Router Dom


推荐阅读