首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >React路由器:从根元素以编程方式路由到路由

React路由器:从根元素以编程方式路由到路由
EN

Stack Overflow用户
提问于 2021-03-23 21:31:22
回答 1查看 34关注 0票数 1

我试图对我的应用程序进行路由,以便当它是任何路由时,比如//listing/foo,我可以使用导航栏的文本框搜索到/search/${search-term}。但是,以编程方式路由的传统方法使用history.push,这在根元素中是不可用的,因为navbar在技术上是在Switch元素之外的。

下面是示例代码:

代码语言:javascript
复制
import {
    HashRouter as Router,
    Switch,
    Route,
    NavLink as Link,
    Redirect
} from 'react-router-dom';
import React from 'react';

class App extends React.Component{
    constructor(){
        this.state = {
            searchTerm: '',
        }
    }

    render(){
        return(
            <>
                <nav>
                    <input className="input" type="text" placeholder="Search listings..." onChange={e => this.startSearching(e)} value={this.state.searchTerm}/>
                </nav>
                <Switch>
                    <Route exact path='/' component={Home} />
                    <Route path='/search/:searchTerm' component={Search} />
                </Switch>
            </>
        )
    }

    startSearching(){
        this.setState({
            searchTerm: e.target.value
        });

        // Omitted debouncing methods
        return (<Redirect push to=`/search/${this.state.searchTerm}` />); // Doesn't work
        this.props.history.push(`/search/${this.state.searchTerm}`) // this.props is undefined
    }
}

如何切换<Switch>中的页面?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-03-23 22:27:42

您可以用withRouter包装导航组件,所以您可以在组件中使用history.push

代码语言:javascript
复制
import React from "react";
import PropTypes from "prop-types";
import { withRouter } from "react-router";

// A simple component that shows the pathname of the current location
class Navbar extends React.Component {
    static propTypes = {
      match: PropTypes.object.isRequired,
      location: PropTypes.object.isRequired,
      history: PropTypes.object.isRequired
};

  render() {
    const { match, location, history } = this.props;

    return <div>You are now at {location.pathname}</div>;
  }
}

// Create a new component that is "connected" (to borrow redux
// terminology) to the router.
const NavbarWithRouter = withRouter(Navbar);

参见https://reactrouter.com/web/api/withRouter的更多详细信息

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/66771594

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档