Javascript 反应按钮点击重定向页面

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/50644976/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 04:39:19  来源:igfitidea点击:

react button onClick redirect page

javascriptreactjsbootstrap-4

提问by Raju yourPepe

I am working on web application using React and bootstrap. When it comes to applying button onClick, it takes me hard time to let my page being redirect to another. if after a href , I cannot go the another page.

我正在使用 React 和 bootstrap 开发 Web 应用程序。在应用 onClick 按钮时,我很难让我的页面重定向到另一个页面。如果在 href 之后,我无法转到另一页。

So would you please tell me is there any need for using react-navigation or other to navigate the page using Button onClick ?

那么请您告诉我是否需要使用 react-navigation 或其他方式使用 Button onClick 导航页面?

import React, { Component } from 'react';
import { Button, Card, CardBody, CardGroup, Col, Container, Input, InputGroup, InputGroupAddon, InputGroupText, Row, NavLink  } from 'reactstrap';

class LoginLayout extends Component {

  render() {
    return (
 <div className="app flex-row align-items-center">
        <Container>
     ...
                    <Row>
                      <Col xs="6">                      
                        <Button color="primary" className="px-4">
                            Login
                         </Button>
                      </Col>
                      <Col xs="6" className="text-right">
                        <Button color="link" className="px-0">Forgot password?</Button>
                      </Col>
                    </Row>
               ...
        </Container>
      </div>
    );
  }
}

采纳答案by May Noppadol

React Router v5.1.2:

反应路由器 v5.1.2:

import { useHistory } from 'react-router-dom';
const App = () => {
   const history = useHistory()
   <i className="icon list arrow left"
      onClick={() => {
        history.goBack()
   }}></i>
}

回答by aravind_reddy

update:

更新

React Router v5 with hooks:

使用钩子响应路由器 v5:

import React from 'react';
import { useHistory } from "react-router-dom";
function LoginLayout() {

  const history = useHistory();

  const routeChange = () =>{ 
    let path = `newPath`; 
    history.push(path);
  }

  return (
      <div className="app flex-row align-items-center">
        <Container>
          ...
          <Row>
            <Col xs="6">                      
              <Button color="primary" className="px-4"
                onClick={routeChange}
                  >
                  Login
                </Button>
            </Col>
            <Col xs="6" className="text-right">
              <Button color="link" className="px-0">Forgot password?</Button>
            </Col>
          </Row>
          ...
        </Container>
      </div>
  );
}
export default LoginLayout;

with React Router v5:

使用 React Router v5:

import { useHistory } from 'react-router-dom';
import { Button, Card, CardBody, CardGroup, Col, Container, Input, InputGroup, InputGroupAddon, InputGroupText, Row, NavLink  } from 'reactstrap';

class LoginLayout extends Component {

  routeChange=()=> {
    let path = `newPath`;
    let history = useHistory();
    history.push(path);
  }

  render() {
    return (
      <div className="app flex-row align-items-center">
        <Container>
          ...
          <Row>
            <Col xs="6">                      
              <Button color="primary" className="px-4"
                onClick={this.routeChange}
                  >
                  Login
                </Button>
            </Col>
            <Col xs="6" className="text-right">
              <Button color="link" className="px-0">Forgot password?</Button>
            </Col>
          </Row>
          ...
        </Container>
      </div>
    );
  }
}

export default LoginLayout;

with React Router v4:

使用 React Router v4:

import { withRouter } from 'react-router-dom';
import { Button, Card, CardBody, CardGroup, Col, Container, Input, InputGroup, InputGroupAddon, InputGroupText, Row, NavLink  } from 'reactstrap';

class LoginLayout extends Component {
  constuctor() {
    this.routeChange = this.routeChange.bind(this);
  }

  routeChange() {
    let path = `newPath`;
    this.props.history.push(path);
  }

  render() {
    return (
      <div className="app flex-row align-items-center">
        <Container>
          ...
          <Row>
            <Col xs="6">                      
              <Button color="primary" className="px-4"
                onClick={this.routeChange}
                  >
                  Login
                </Button>
            </Col>
            <Col xs="6" className="text-right">
              <Button color="link" className="px-0">Forgot password?</Button>
            </Col>
          </Row>
          ...
        </Container>
      </div>
    );
  }
}

export default withRouter(LoginLayout);

回答by Waleed Qidan

Don't use a button as a link. Instead, use a link styled as a button.

不要使用按钮作为链接。相反,使用样式为按钮的链接。

<Link to="/signup" className="btn btn-primary">Sign up</Link>

回答by Matteus Barbosa

I was trying to find a way with Redirect but failed. Redirecting onClick is simpler than we think. Just place the following basic JavaScript within your onClick function, no monkey business:

我试图找到重定向的方法,但失败了。重定向 onClick 比我们想象的要简单。只需将以下基本 JavaScript 放在您的 onClick 函数中,不要乱搞:

window.location.href="pagelink"

回答by rudresh solanki

This can be done very simply, you don't need to use a different function or library for it.

这可以非常简单地完成,您不需要为它使用不同的函数或库。

onClick={event =>  window.location.href='/your-href'}

回答by Kareem Khaleel

A very simple way to do this is by the following:

一个非常简单的方法是通过以下方式:

onClick={this.fun.bind(this)}

and for the function:

和功能:

fun() {
  this.props.history.push("/Home");
}

finlay you need to import withRouter:

finlay 你需要用路由器导入:

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

and export it as:

并将其导出为:

export default withRouter (comp_name);

回答by Maheshvirus

useHistory()from react-router-domcan fix your problem

useHistory()fromreact-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;

回答by thenewbieprogrammer

I was also having the trouble to route to a different view using navlink.

我也无法使用导航链接路由到不同的视图。

My implementation was as follows and works perfectly;

我的实现如下并且完美运行;

<NavLink tag='li'>
  <div
    onClick={() =>
      this.props.history.push('/admin/my- settings')
    }
  >
    <DropdownItem className='nav-item'>
      Settings
    </DropdownItem>
  </div>
</NavLink>

Wrap it with a div, assign the onClick handler to the div. Use the history object to push a new view.

用 div 包裹它,将 onClick 处理程序分配给 div。使用历史对象推送新视图。

回答by Oben Desmond

First, import it:

首先,导入它:

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

Then, in function or class:

然后,在函数或类中:

const history = useHistory();

Finally, you put it in the onClickfunction:

最后,你把它放在onClick函数中:

<Button onClick={()=> history.push("/mypage")}>Click me!</Button>

回答by Harsha N Hegde

With React Router v5.1:

使用 React Router v5.1:

import {useHistory} from 'react-router-dom';
import React, {Component} from 'react';
import {Button} from 'reactstrap';
.....
.....
export class yourComponent extends Component {
    .....
    componentDidMount() { 
        let history = useHistory;
        .......
    }

    render() {
        return(
        .....
        .....
            <Button className="fooBarClass" onClick={() => history.back()}>Back</Button>

        )
    }
}