即使在React(Router)中也是如此,如何去另一个域/路由

问题描述 投票:0回答:2

如果Home组件包含一个按钮,并且我希望单击该按钮,它将转到另一个Route(域)。例如-选择组件?我该怎么办?

主要组成部分:

function App() {
  return (
    <Router> {/*Everything inside this will be capble to routing*/}
    <div className="App">
    <h1>CarLeas</h1>
    <Switch>
      <Route path="/" exact component={Home}/>
      <Route path="/choose" component={Choose}/>
      <Route path="/whochoose" component={Whochoose}/>
      <Route path="/reback" component={Reback}/>
    </Switch>

    </div>
    </Router>
  );
}

主页组件:

import React from "react";

class Home extends React.Component {
    render() {
        return (
        <div>
            <img src="https://www.trustford.co.uk/img/campaigns/all-new-ford-focus/2018-08-22/all-new-focus-banner-2000x500.jpg"></img>
            <p>Rent a Car</p>
            <button>Start Now</button> {/*Button - If event onclick happend show the "choose" component*/}
        </div>
        )
    }

}

export default Home;
reactjs routing react-router
2个回答
1
投票

您可以使用this.props.history.push()以编程方式切换路由:

this.props.history.push("/choose");

但是,如果没有其他逻辑,我建议您使用<Link>中的react-router进行链接:

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

class Home extends React.Component {
    render() {
        return (
        <div>
            <img src="https://www.trustford.co.uk/img/campaigns/all-new-ford-focus/2018-08-22/all-new-focus-banner-2000x500.jpg"></img>
            <p>Rent a Car</p>
            <Link to="/choose">Start Now</Link> 
        </div>
        )
    }

}
export default Home;

0
投票

import React from "react";

class Home extends React.Component {
    render() {
        const { history } = this.props;
        return (
        <div>
            <img src="https://www.trustford.co.uk/img/campaigns/all-new-ford-focus/2018-08-22/all-new-focus-banner-2000x500.jpg"></img>
            <p>Rent a Car</p>
            <button onClick={()=> history.push('/choose') }>Start Now</button>}
        </div>
        )
    }

}

export default Home;
© www.soinside.com 2019 - 2024. All rights reserved.