最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to handle the navigation for the Button click in ReactJS? - Stack Overflow

programmeradmin0浏览0评论

I am implementing a new app. Currently, I am able to do the navigation for the Link and couldn't do it for the button click navigation. I have checked this post and tried with BrowserHistory option. But this method is currently not supported.

Code:

import React, { Component } from "react";
import {Route,Router,NavLink,HashRouter,BrowserRouter} from "react-router-dom";
import Contact from "./components/Contact";
import Home from "./components/Home";
import EnquiryResult from "./components/EnquiryResult";
import logo from './logo.svg';
import './App.css';

class MainStack extends Component {

  onClick(){
   // browserHistory.push("/EnquiryResult");
}

  render() {
    return (
        <div>
        <header className="App-header">
          <img src={logo} className="App-logo" alt="logo" />
          <h1 className="App-title">Welcome to React</h1>
        </header>
        <div>
          <button className="btn" onClick={this.onClick.bind(this)}>Enquiry</button >
          </div>

          <ul className="header">
            <li><NavLink  to="/contact">Contact</NavLink ></li>
            <li><NavLink  to="/Home">Home</NavLink ></li>
          </ul>

          <div>
            <Route path="/Home" component={Home}/>
            <Route path="/contact" component={Contact}/>
            <Route path="/EnquiryResult" component={EnquiryResult}/>

        </div>
        </div>
    );
  }
}

export default MainStack;

navigation is working fine for the contact and Home. But couldn't achieve the navigation for the Enquiry. How can I achieve this button navigation?

I am implementing a new app. Currently, I am able to do the navigation for the Link and couldn't do it for the button click navigation. I have checked this post and tried with BrowserHistory option. But this method is currently not supported.

Code:

import React, { Component } from "react";
import {Route,Router,NavLink,HashRouter,BrowserRouter} from "react-router-dom";
import Contact from "./components/Contact";
import Home from "./components/Home";
import EnquiryResult from "./components/EnquiryResult";
import logo from './logo.svg';
import './App.css';

class MainStack extends Component {

  onClick(){
   // browserHistory.push("/EnquiryResult");
}

  render() {
    return (
        <div>
        <header className="App-header">
          <img src={logo} className="App-logo" alt="logo" />
          <h1 className="App-title">Welcome to React</h1>
        </header>
        <div>
          <button className="btn" onClick={this.onClick.bind(this)}>Enquiry</button >
          </div>

          <ul className="header">
            <li><NavLink  to="/contact">Contact</NavLink ></li>
            <li><NavLink  to="/Home">Home</NavLink ></li>
          </ul>

          <div>
            <Route path="/Home" component={Home}/>
            <Route path="/contact" component={Contact}/>
            <Route path="/EnquiryResult" component={EnquiryResult}/>

        </div>
        </div>
    );
  }
}

export default MainStack;

navigation is working fine for the contact and Home. But couldn't achieve the navigation for the Enquiry. How can I achieve this button navigation?

Share Improve this question edited Apr 16, 2024 at 12:24 DINA TAKLIT 8,38810 gold badges83 silver badges90 bronze badges asked Jun 14, 2018 at 6:52 SubburajSubburaj 2,3343 gold badges22 silver badges39 bronze badges 2
  • Is your MainStack wrapped in BrowserRouter or not? – devserkan Commented Jun 14, 2018 at 7:20
  • yeah. MainStack is wrapped with BrowserRouter . – Subburaj Commented Jun 14, 2018 at 7:25
Add a comment  | 

5 Answers 5

Reset to default 7

Using useHistory() from react-router-dom

import React from 'react';
import { useHistory } from "react-router-dom";
function NavigationDemo() {
  const history = useHistory();
  const navigateTo = () => history.push('/componentURL');//eg.history.push('/login');

  return (
   <div>
   <button onClick={navigateTo} type="button" />
   </div>
  );
}
export default NavigationDemo;

If your MainStack is wrapped in BrowserRouter you can use history like this:

onClick = () => this.props.history.push("/EnquiryResult");

And for the button:

<button className="btn" onClick={this.onClick}>Enquiry</button>
// No need to bind since we are using arrow function for our onClick.

Correct way to navigate using context in react-router v4:

this.context.router.history.push('/EnquiryResult')

The new react-router v4 has changed the location of the push method when accessing this.context.router. router now has history and route as properties and it is within history that you will find the allocated method.

Also, if you are using the latest react version 15.5.0, propTypes have been removed into a separate package and you can get them with:

npm install prop-types --save

or

yarn add prop-types

Change the code like below

onClick(){
   this.context.router.history.push('/EnquiryResult')
}

Additionally, contextTypes needs to be declared as below

  static contextTypes = {
    router: PropTypes.object
  }

In react-router-dom v6 useHistory() function is replaced by useNavigate(). So using useHistory will lead you to this error:

Attempted import error: 'useHistory' is not exported from 'react-router-dom'

So just replace useHistory with useNavigate ex:

import { useNavigate } from 'react-router-dom'
export default function QuestionAnswer() {
    const navigate = useNavigate()
    return (
          <Button
                onClick={() => {
                  navigate(`/something`)
                }}
              >
                Click Me
          </Button>
    )
}

See more detail in this Attempted import error: 'useHistory' is not exported from 'react-router-dom' question

You will need to import from react-router in order to get browserHistory work

import {browserHistory} from 'react-router';

Should work now

 onClick(){
   browserHistory.push("/EnquiryResult");
 }
发布评论

评论列表(0)

  1. 暂无评论