我试图对我的应用程序进行路由,以便当它是任何路由时,比如/或/listing/foo,我可以使用导航栏的文本框搜索到/search/${search-term}。但是,以编程方式路由的传统方法使用history.push,这在根元素中是不可用的,因为navbar在技术上是在Switch元素之外的。
下面是示例代码:
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>中的页面?
发布于 2021-03-23 22:27:42
您可以用withRouter包装导航组件,所以您可以在组件中使用history.push
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://stackoverflow.com/questions/66771594
复制相似问题