Controlled Component
13219 ワード
Controlled Component
React Component管理
import { useCallback, useState } from "react";
export default function InputSample(){
const [inputs, setInputs] = useState({
name:'',
nickname:''
});
const {name, nickname} = inputs
const onChange = useCallback((e:React.ChangeEvent<HTMLInputElement>)=>{
const {name, value} = e.target
setInputs(prev=>({
...prev,
[name]:value
}))
},[])
return (
<form>
<input placeholder="이름" name="name" value={name} onChange={onChange}/>
<input placeholder="닉네임" name="nickname" value={nickname} onChange={onChange}/>
<div>
<b>값 : </b>
{name} - {nickname}
</div>
</form>
)
}
Uncontrolled Component
import { useCallback, useRef } from "react";
export default function UnControlledInput(){
//React.LegacyRef<HTMLInputElement>
const nameInput = useRef<HTMLInputElement>(null);
const nicknameInput = useRef<HTMLInputElement>(null);
const onClick = useCallback((e:React.MouseEvent<HTMLButtonElement>)=>{
e.preventDefault()
const name = nameInput.current?.value
const nickname = nicknameInput.current?.value
console.log(name)
console.log(nickname)
},[])
return (
<form>
<input
ref={nameInput}
/>
<input
ref={nicknameInput}/>
<div>
<b>값 : </b>
</div>
<button onClick={onClick}>button</button>
</form>
)
}
Reference
この問題について(Controlled Component), 我々は、より多くの情報をここで見つけました https://velog.io/@akatapata/Controlled-Componentテキストは自由に共有またはコピーできます。ただし、このドキュメントのURLは参考URLとして残しておいてください。
Collection and Share based on the CC Protocol