【问题标题】:react button onClick redirect page反应按钮 onClick 重定向页面
【发布时间】:2018-11-11 16:29:45
【问题描述】:

我正在使用 React 和引导程序开发 Web 应用程序。在应用按钮 onClick 时,我很难让我的页面被重定向到另一个页面。如果在一个 href 之后,我不能去另一个页面。

那么您能否告诉我是否需要使用 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>
    );
  }
}

【问题讨论】:

标签: javascript reactjs bootstrap-4


【解决方案1】:

更新

React Router 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:

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;

使用 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;

使用 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);

【讨论】:

  • 使用上述代码后,我仍然在同一页面上。除此之外,我还需要做任何额外的工作吗?
  • 我想没有.. 你用withRouter 包裹你的组件了吗?
  • 您可以添加沙箱并提供链接,以便我更好地解决您的问题
  • 在 v5.1.2 中不能使用钩子来做到这一点。 React Hook "useHistory" is called in function "routeChange" which is neither a React function component or a custom React Hook function. 编辑:如果您遇到此问题,请将 const history = useHistory() 移出处理程序。
  • 不确定这是否有用,但如果您正在使用或计划使用 React 路由器 v6,则不能再使用useHistory。他们已将其替换为useNavigateconst navigate = useNavigate(); navigate('../edit') 这将从 /some/path/profile 移动到 /some/path/edit
【解决方案2】:

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

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

【讨论】:

  • 我收到一个错误,不确定是否与此有关,link is a void element tag and must neither have `children` nor use `dangerouslySetInnerHTML`.
  • 这不是问题。
【解决方案3】:

反应路由器 v5.1.2:

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

【讨论】:

  • 我已经在 'const history = useHistory()' 行上失败了,因为'TypeError:无法读取未定义的属性'历史'。你在 index.js 中使用了 react-router-dom 的任何东西吗?
【解决方案4】:

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

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

【讨论】:

  • 注意:这将重新加载页面。
  • @JamesPoulose 完全正确!在不重新加载整个页面的情况下推荐的方法是什么?我说的是路由onClick。例如,当我单击详细信息图标时。提前致谢
  • 这有点慢,如果与功能组件的 useHistory 挂钩相比。重新加载可能是原因
【解决方案5】:

我试图找到一种使用 Redirect 的方法但失败了。重定向 onClick 比我们想象的要简单。只需将以下基本 JavaScript 放在您的 onClick 函数中即可,无需多言:

window.location.href="pagelink"

【讨论】:

  • 注意:这将重新加载页面。
  • 是的,这违背了使用 react 制作单页应用程序的目的,将使您所有的 react 代码被重新发送等(历史之类的东西可能会被重置)
【解决方案6】:

首先,导入它:

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

然后,在函数或类中:

const history = useHistory();

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

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

【讨论】:

    【解决方案7】:

    执行此操作的一个非常简单的方法是:

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

    对于函数:

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

    你需要用Router导入的finlay:

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

    并将其导出为:

    export default withRouter (comp_name);
    

    【讨论】:

      【解决方案8】:

      react-router-domuseHistory() 可以解决您的问题

      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;
      

      【讨论】:

        【解决方案9】:

        如果上述所有方法都失败了,请使用以下内容:

            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()}
                        </>
                    )
                }
            }
        

        【讨论】:

          【解决方案10】:

          如果您想在 Click 事件上重定向到路由。

          就这样做

          在功能组件中

          props.history.push('/link')
          

          在类组件中

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

          例子:

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

          测试日期:

          react-router-dom: 5.2.0,

          反应:16.12.0

          【讨论】:

            【解决方案11】:

            如果你已经创建了一个类来定义你的 Button 的属性(如果你已经创建了一个按钮类),并且你想在另一个类中调用它并通过你在这个 new 中创建的按钮将它链接到另一个页面类,只需导入您的“按钮”(或按钮类的名称)并使用以下代码:

            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
            

            【讨论】:

              【解决方案12】:

              按钮上的一个简单的点击处理程序,并设置window.location.hash 就可以了,假设您的目的地也在应用程序内。

              你可以在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>
                  );
                }
              }
              

              【讨论】:

              • 对于希望维护任何形式的 SPA(单页应用程序)的人来说,使用 window.location 是不可取的。您更改了浏览器的 url 并清除了任何状态等。
              • 当您说“消灭任何国家”时,您具体指的是什么?我正在使用location.hash,它不会导致页面重新加载。
              【解决方案13】:

              使用 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>
              
                      )
                  }
              }
              
              

              【讨论】:

                【解决方案14】:

                我也无法使用 navlink 路由到不同的视图。

                我的实现如下,效果很好;

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

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

                【讨论】:

                  【解决方案15】:

                  确保从“react-router-dom”导入 {Link}; 而且只是超链接而不是使用函数。

                  import {Link} from "react-router-dom";
                  
                  <Button>
                     <Link to="/yourRoute">Route Name</Link>
                  </Button>
                  

                  【讨论】:

                    猜你喜欢
                    • 2015-12-02
                    • 2022-12-03
                    • 1970-01-01
                    • 1970-01-01
                    • 2014-08-20
                    • 2021-11-12
                    • 1970-01-01
                    • 1970-01-01
                    • 2014-05-21
                    相关资源
                    最近更新 更多