简体   繁体   English

如何在 ReactJS 中重定向按钮点击

[英]How to redirect on button click in ReactJS

I want to redirect to './createadd.js' on click (when the function runs).我想在单击时重定向到“./createadd.js”(当函数运行时)。 How can I?我怎样才能? i have tried using history.push() and react router but none works.我曾尝试使用 history.push() 和 react router,但没有任何效果。

APP.JS: APP.JS:

import { render } from '@testing-library/react';
import React from 'react';

class App extends React.Component {
  render(){

  this.selladd = () => {     //Function to redirect to another page

  }

  return (
  <div style={{position: "absolute", left: 1300, top: 25, overflowX: "hidden"}}>
    <button onClick={this.selladd}>Sell</button>
  </div>);
    }
}

export default App;

You can use both the link and the history.push()您可以同时使用链接和 history.push()

 import { render } from '@testing-library/react';
    import React, { Component } from 'react';
    
    class App extends React.Component {
 constructor(props) {
        super(props);
this.selladd =this.selladd .bind(this);
}
selladd (){
 this.props.history.push({ pathname: ''  })
}
      render(){

      return (
      <div style={{position: "absolute", left: 1300, top: 25, overflowX: "hidden"}}>
        <button onClick={this.selladd}>Sell</button>
      </div>);
        }
    }

or或者

import { Link } from 'react-router-dom';
     <Link to={{ pathname: '' }}  >
     <button onClick={this.selladd}>Sell</button>
      </Link>

You need to redirect to another component which is in file createadd.js right.您需要重定向到文件 createadd.js 中的另一个组件。

Wrap your component as:将您的组件包装为:

export default withRouter(App)

And add a path to your routes such as:并为您的路线添加路径,例如:

<Route exact path='/createadd' component={CreateAddComponent} />

Where CreateAddComponent, is you component imported from the createadd.js file.其中 CreateAddComponent 是您从 createadd.js 文件导入的组件。

Then in your function, just do然后在您的功能中,只需执行

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

You can redirect to any of the pages using您可以使用重定向到任何页面

this.props.history.push("your link here");

Or if you are using react-router-dom, you can also use或者,如果您使用的是 react-router-dom,您也可以使用

<Redirect to="path" />

Or why don't you just wrap your button inside a href tag.或者你为什么不把你的按钮包裹在一个 href 标签中。

<a href ="link"> 
   <button>Click Here</button>
</a>

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

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