Skip to content

Instantly share code, notes, and snippets.

@ponko23
Last active September 18, 2019 12:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ponko23/ba31fdf703a84b76825a55582247ad46 to your computer and use it in GitHub Desktop.
Save ponko23/ba31fdf703a84b76825a55582247ad46 to your computer and use it in GitHub Desktop.
import { useState } from 'react'
export const useField = (type) => {
const [value, setValue] = useState('')
const onChange = (event) => {
setValue(event.target.value)
}
// 値をクリアしたい!
const reset = () => {
setValue('')
}
return {
type,
value,
onChange,
reset
}
}
↑これを
const name = useField('text')
<input {...name} />
こうして
name.reset()
これでinputの中身を空にしたいのですが、
Invalid value for prop reset' on <input> tag
って怒られるので、
<input {...name} reset='' />
と上書きしてごまかしているのですが、カッコ悪い…
hooksの戻り値を
return [
{ type, value, onChange },
reset
]
とすれば
const [name, nameReset] = useField('text')
と定義でき、
<input {...name} />
だけでprops指定、
nameReset()
で値のクリアができた
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment