当用户在输入字段上按下 Enter 键时,我试图重定向到新路由。我有一个标题和搜索组件,我想在每个页面上呈现它。我发现使用 Redirect 组件、withRouter 组件、使用上下文以及可能将历史对象传递给我的 Search 组件(输入字段所在的位置)的不同用例。任何帮助,将不胜感激..
App.js(主要组件)
import React, { Component } from 'react';
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
import Title from './Title';
import Search from './Search';
import Home from './Home';
import Movie from './Movie';
class App extends Component {
render() {
return (
<div>
<Title />
<Search />
<Router>
<Switch>
<Route exact path='/' component={Home} />
<Route path='/movie' component={Movie} />
</Switch>
</Router>
</div>
);
}
}
export default App;
Search.js(输入组件)
import React, { Component } from 'react';
import './Search.css';
class Search extends Component {
constructor(props) {
super(props);
this.state = {
value: ""
}
this.handleChange = this.handleChange.bind(this);
}
handleChange(event) {
this.setState({value: event.target.value});
}
handleSubmit(e) {
if (e.key === 'Enter') {
// TODO redirect user to '/movie'
}
}
render() {
return (
<input type="text" id="searchTitle" placeholder="Search for a movie" onChange={this.handleChange} onKeyPress={this.handleSubmit} value={this.state.input} />
)
}
}
export default Search;