Last active
September 18, 2019 12:02
-
-
Save ponko23/ba31fdf703a84b76825a55582247ad46 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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