作用:自定义hook是内置hook与自定义逻辑组合的以use开头的函数,以标准封装的形式 ,达到共享逻辑的目的。
用法:类似于内置hook。
示例:
import React, { useState } from 'react'
function useUpdateInput(initialValue) {
const [value, setValue] = useState(initialValue)
return {
value,
onChange: e => setValue(e.target.value)
}
}
function App() {
const usenameInput = useUpdateInput('')
const passwordInput = useUpdateInput('')
const submitForm = e => {
e.preventDefault()
console.log(usenameInput.value)
console.log(passwordInput.value)
}
return (
<form onSubmit={submitForm}>
<input type="text" name="usename" {...usenameInput} />
<input type="password" name="password" {...passwordInput} />
<input type="submit" />
</form>
)
}
export default App