【发布时间】:2019-08-14 13:08:37
【问题描述】:
我正在尝试在具有多个页面的应用程序中创建一个搜索页面,我使用 react router v5。
我的问题如下,我想在文本字段为空时返回上一页,否则如果输入字段中有条目,我想返回搜索页面('/search')
提前感谢您的帮助和回答。
所以我使用 goBack 和 push 道具。 但是即使字段为空也不能返回上一页
我的组件 Routes.js
const Routes = (props) => {
return (
<div>
<Route exact path="/" component={Home} />
<Route
exact
path='/search'
component={() => <Search query={props.text} />}
/>
<Route path="/film/:id" component={MovieDetail} />
<Route path="/FavorisList" component={WatchList} />
<Route path="/search/:search" component={Search} />
<Route path="*" component={NotFound} />
</div>
)}
我的组件 SearchBar.js
class SearchBar extends React.Component {
constructor(props) {
super(props);
this.state = {
inputValue:'',
};
}
handleChange = (event) => {
if(event.target.value === '') {
this.props.history.goBack()
return;
}
if(event.target.value.length){
this.props.history.push("/search")
this.search(event.target.value)
}
}
search = (query) => {
//search results retrieved with redux
this.props.applyInitialResult(query, 1)
}
render() {
return (
<div>
<input
type="text"
value={this.state.inputValue}
placeholder="Search movie..."
className={style.field}
onChange={this.handleChange.bind(this)}
/>
</div>
);
}
export default SearchBar;
组件 App.js
class App extends React.Component {
render(){
return (
<div>
<BrowserRouter>
<NavBar />
<Routes/>
</BrowserRouter>
</div>
);
}
}
export default App;
【问题讨论】:
-
你有什么错误吗?
-
不,我没有错误消息,我有意外的行为,如果我输入一个字符,则返回完成,但是当我输入更长的术语(如“不可能完成的任务”)时,返回不再完成.
-
我在您的路线中没有看到对
SearchBar的任何引用。您的应用程序中是否使用了SearchBar组件? -
我的搜索栏已集成在我的导航栏中,如果有帮助,我会使用 App 组件更新我的帖子
标签: reactjs