接上篇:
问题:
如果使用 this.props.history.push('/searchs') ,它是有问题的,导致不能跳转,因为没有props,需要使用withRouter为这个对象添加history这个对象方可使用
这个问题的解决方案就是:
/*
* 创建时间: 2019-09-19 14:42
* 作者:南宫伯赏
* 功能: 针对搜索功能的NavBar
* */
import * as React from 'react';
import './searchNavBar.scss';
import { withRouter } from 'react-router-dom';
class SearchNavBar extends React.Component<any, any>{
constructor(props: any) {
super(props)
this.state = {
searchValue: ''
}
}
public render() {
return (<div className='navbar'>
<div className='navbar-box'>
<div className='navbar-box-first'>
<div className='navbar-left'>
<div className='icon-back'>
<span onClick={this.goBacks} className="back iconfont icon-fanhui5"></span>
</div>
</div>
<div className='navbar-center'>
<div className='navbar-input'>
<div className='search-first'>
<span onClick={this.search} className="search-icon iconfont icon-sousuo5"></span>
</div>
<div className='search-second'>
<input onChange={(e) => this.setValue(e)} value={this.state.searchValue} className='input' type="input" placeholder='大闸蟹'/>
</div>
<div className='icon-delete'>
<div className='delete'>
<span onClick={this.deleteValue} className='deleted iconfont icon-chuyidong'></span>
</div>
</div>
</div>
</div>
<div className='navbar-right'>
<div className='icon-shares'>
<p className='search' onClick={this.search}>搜索</p>
{/*<span className='share iconfont icon-fenxiang11'></span>*/}
</div>
</div>
</div>
</div>
<div className='pt44'></div>
</div>);
}
public goBacks = () => { // 使用时候注意this
this.props.history.goBack()
}
public search = () => {
alert('搜索内容为空')
}
public deleteValue = () => { // 清空输入框内容
this.setState(() => ({
searchValue: ''
}))
}
public setValue (e:any) { //
const value = e.target.value
this.setState(() => ({
searchValue: value
}))
}
}
export default withRouter(SearchNavBar)
我们在使用this.props.hostory.push的时候,其实是没有history这个对象的,需要在使用withRouter这个包裹之后,方能使用
那withRouter其实就是为对象添加一下这几个对象的:
history: H.History;
location: H.Location<S>;
match: match<Params>;
staticContext?: C;
详细情况可以看源码了解,
以上源代码的问题和解决方式都在React-TS项目源码
项目github地址: https:// github.com/focusdroid/m eiriyouxian_react_ts