页面跳转 不刷新

能跳页面但不刷新 利用 pushState 或者 replaceState
先在函数组件最外层 写上:

var _wr = function(type) {
  var orig = window.history[type]
  return function() {
      var rv = orig.apply(this, arguments)
     var e = new Event(type)
      e.arguments = arguments
      window.dispatchEvent(e)
      return rv
  }
}
window.history.pushState = _wr('pushState')
window.history.replaceState = _wr('replaceState')
export default To

之后

//按钮
<button onClick={onClick}>点我</button>
//事件

  const onClick = () => {
  	// 两种写法
  	
  	//这个是替换没有返回
    // window.history.replaceState({name: '123'},'xxx','/go')
    //                               ⬆            ⬆     ⬆
    //                            传的值        随便写 路由
    
    //这个有返回
    window.history.pushState({name: '123'},'xxx','/go') 
    //                          ⬆            ⬆     ⬆
    //                       传的值        随便写 路由
  }
//根据hook监听 取值
const [pop,setPop] = React.useState(null) //默认啥也没有
  React.useEffect(() => {
    window.addEventListener('pushState', evt => {
      if(evt.arguments[2].includes('/go')){ //判断路由 有的话就写组件 或者 元素
        setPop(<h1>h1h1h1h1h1</h1>)//之后能渲染倒对应的页面上
      }
      console.log(window.history.state,1);
      //取的传过去的值
    })
  },[])

关于css-modules
好处是 当文件引入之后class不会重复 会有一个唯一的哈希值

1. 创建一个 style.module.less //名字必须这个
2. import styles from './style.module.less'
3. <h1 className={styles.move}>123465798</h1>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值