简体   繁体   English

反应按钮 onClick 重定向页面

[英]react button onClick redirect page

I am working on a web application using React and bootstrap.我正在使用 React 和 bootstrap 开发一个 Web 应用程序。 When it comes to applying button onClick, I'm having a hard time to have page being redirect to another.在应用按钮 onClick 时,我很难将页面重定向到另一个页面。 If after a href, I cannot go the another page.如果在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>
    );
  }
}
 

update :更新

React Router v6 :反应路由器 v6

import React from 'react';
import { useNavigate } from "react-router-dom";
function LoginLayout() {
  
  let navigate = useNavigate(); 
  const routeChange = () =>{ 
    let path = `newPath`; 
    navigate(path);
  }
  
  return (
     <div className="app flex-row align-items-center">
      <Container>
      ...          
          <Button color="primary" className="px-4"
            onClick={routeChange}
              >
              Login
            </Button>
      ...
       </Container>
    </div>
  );
}}

React Router v5 with hooks:带有钩子的 React Router 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 路由器 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 路由器 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);

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>

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>
}

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

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

I was trying to find a way with Redirect but failed.我试图找到一种使用 Redirect 的方法,但失败了。 Redirecting onClick is simpler than we think.重定向 onClick 比我们想象的要简单。 Just place the following basic JavaScript within your onClick function, no monkey business:只需将以下基本 JavaScript 放在您的 onClick 函数中,无需任何操作:

window.location.href="pagelink"

First, import it:首先,导入它:

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

Then, in function or class:然后,在函数或类中:

const history = useHistory();

Finally, you put it in the onClick function:最后,你把它放在onClick函数中:

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

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 你需要用Router导入:

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

and export it as:并将其导出为:

export default withRouter (comp_name);

useHistory() from react-router-dom can fix your problem react-router-dom中的useHistory()可以解决您的问题

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 all above methods fails use something like this:如果上述所有方法都失败,请使用以下内容:

    import React, { Component } from 'react';
    import { Redirect } from "react-router";
    
    export default class Reedirect extends Component {
        state = {
            redirect: false
        }
        redirectHandler = () => {
            this.setState({ redirect: true })
            this.renderRedirect();
        }
        renderRedirect = () => {
            if (this.state.redirect) {
                return <Redirect to='/' />
            }
        }
        render() {
            return (
                <>
                    <button onClick={this.redirectHandler}>click me</button>
                    {this.renderRedirect()}
                </>
            )
        }
    }

if you want to redirect to a route on a Click event.如果要重定向到 Click 事件上的路由。

Just do this就这样做

In Functional Component在功能组件中

props.history.push('/link')

In Class Component在类组件

this.props.history.push('/link')

Example:例子:

<button onClick={()=>{props.history.push('/link')}} >Press</button>

Tested on:测试:

react-router-dom: 5.2.0,反应路由器域:5.2.0,

react: 16.12.0反应:16.12.0

If you already created a class to define the properties of your Button (If you have a button class created already), and you want to call it in another class and link it to another page through a button you created in this new class, just import your "Button" (or the name of your button class) and use the code below:如果您已经创建了一个类来定义 Button 的属性(如果您已经创建了一个按钮类),并且您想在另一个类中调用它并通过您在这个新类中创建的按钮将其链接到另一个页面,只需导入您的“按钮”(或按钮类的名称)并使用以下代码:

import React , {useState} from 'react';
import {Button} from '../Button';

function Iworkforbutton() {
const [button] = useState(true);

return (
    <div className='button-class'>
        {button && <Button onClick={()=> window.location.href='/yourPath'}
            I am Button </Button>
    </div>
    )
}

export default Iworkforbutton

A simple click handler on the button, and setting window.location.hash will do the trick, assuming that your destination is also within the app.一个简单的按钮点击处理程序,并设置window.location.hash就可以了,假设您的目的地也在应用程序内。

You can listen to the hashchange event on window , parse the URL you get, call this.setState() , and you have your own simple router, no library needed .你可以在window上监听hashchange事件,解析你得到的 URL,调用this.setState() ,你就有了自己的简单路由器,不需要库

class LoginLayout extends Component {
    constuctor() {
      this.handlePageChange = this.handlePageChange.bind(this);
      this.handleRouteChange = this.handleRouteChange.bind(this);
      this.state = { page_number: 0 }
    }

  handlePageChange() {
    window.location.hash = "#/my/target/url";
  }

  handleRouteChange(event) {
    const destination = event.newURL;
    // check the URL string, or whatever other condition, to determine
    // how to set internal state.
    if (some_condition) {
      this.setState({ page_number: 1 });
    }
  }

  componentDidMount() {
    window.addEventListener('hashchange', this.handleRouteChange, false);
  }

  render() {
    // @TODO: check this.state.page_number and render the correct page.
    return (
      <div className="app flex-row align-items-center">
        <Container>
          ...
                <Row>
                  <Col xs="6">                      
                    <Button 
                       color="primary"
                       className="px-4"
                       onClick={this.handlePageChange}
                    >
                        Login
                     </Button>
                  </Col>
                  <Col xs="6" className="text-right">
                    <Button color="link" className="px-0">Forgot password </Button>
                  </Col>
                </Row>
           ...
        </Container>
      </div>
    );
  }
}

With React Router v5.1:使用 React 路由器 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>

        )
    }
}

I was also having the trouble to route to a different view using navlink.我也很难使用 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.用 div 包装它,将 onClick 处理程序分配给 div。 Use the history object to push a new view.使用历史对象推送新视图。

Make sure to import {Link} from "react-router-dom";确保从“react-router-dom”导入 {Link}; And just hyperlink instead of using a function.并且只是超链接而不是使用函数。

import {Link} from "react-router-dom";

<Button>
   <Link to="/yourRoute">Route Name</Link>
</Button>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM