react使用link跳转传递参数_React-Typescript之路由跳转(使用this.props.history.push)

edecd0a994084c1fb1934b67105562c0.png

接上篇:

问题:

如果使用 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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值