能跳页面但不刷新 利用 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>