自定义hooks(参照链接)
类useState方法的实现,起一个文件useForm.js 在里面自维护data和方法,后面返回一个数组即可
function useForm(init){
const [value,setValue]=useState(init);
const handleChange=(e)=>{
setValue({...value,[e.targe.name]:e.target.value})
}
const resetValue=()=>{
setValue(init)
}
return [init,handleChange,resetChange ]
}
使用
import useForm from './useForm'
const [init,handleChange,resetChange ] = useForm({name:'',age:''})
"通过使用自定义 Hooks,我们可以将表单逻辑从组件中提取出来,使代码更加可重用和简洁。这使得我们可以在其他组件中轻松地使用相同的表单逻辑。"
### useScroll
import { useState, useEffect } from 'react'
const useScroll = (scrollRef) => {
const [pos, setPos] = useState([0,0])
useEffect(() => {
function handleScroll(e){
setPos([scrollRef.current.scrollLeft, scrollRef.current.scrollTop])
}
scrollRef.current.addEventListener('scroll', handleScroll, false)
return () => {
scrollRef.current.removeEventListener('scroll', handleScroll, false)
}
}, [])
return pos
}
export default useScroll
import React, { useRef } from 'react'
import { useScroll } from 'hooks'
const Home = (props) => {
const scrollRef = useRef(null)
const [x, y] = useScroll(scrollRef)
return <div>
<div ref={scrollRef}>
<div className="innerBox"></div>
</div>
<div>{ x }, { y }</div>
</div>
}
Vue2里methods为什么不可以用箭头函数
箭头函数没有自己的
this。它们不适合定义对象方法。箭头函数体内的this对象,就是定义时所在的对象,而不是使用时所在的对象。所以箭头函数的this是固定的,不能改变或者重新绑定,Vue官方文档发现已经提醒用户不要使用箭头函数: