๐จย ์ค๋์ ref์ ๋ํด์ ๊ณต๋ถํ๊ธฐ,,,,
=ย ref๋ ์๋นํ ๊ฐ๋ ฅํ ์์ด๋ค.
๐ย ๊ธฐ๋ณธ ์ํ์์์ ref๋ ๋ค๋ฅธ DOM์์๋ก ์์ธ์คํด์ ์์ ํ ์ ์๊ฒ ํด์ฃผ๋ ์ญํ ์ด๋ค.
์์)
import React, { useState } from "react";
import Card from "../UI/Card";
import Button from "../UI/Button";
import ErrorModal from "../UI/ErrorModal";
import Wrapper from "../Helpers/Wrapper";
import classes from "./AddUser.module.css";
const AddUser = (props) => {
const [enteredUsername, setEnteredUsername] = useState("");
const [enteredAge, setEnteredAge] = useState("");
const [error, setError] = useState();
const addUserHandler = (event) => {
event.preventDefault();
if (enteredUsername.trim().length === 0 || enteredAge.trim().length === 0) {
setError({
title: "Invalid input",
message: "Please enter a valid name and age (non-empty values).",
});
return;
}
if (+enteredAge < 1) {
setError({
title: "Invalid age",
message: "Please enter a valid age (> 0).",
});
return;
}
props.onAddUser(enteredUsername, enteredAge);
setEnteredUsername("");
setEnteredAge("");
};
const usernameChangeHandler = (event) => {
setEnteredUsername(event.target.value);
};
const ageChangeHandler = (event) => {
setEnteredAge(event.target.value);
};
const errorHandler = () => {
setError(null);
};
return (
<Wrapper>
{error && (
<ErrorModal
title={error.title}
message={error.message}
onConfirm={errorHandler}
/>
)}
<Card className={classes.input}>
<form onSubmit={addUserHandler}>
<label htmlFor="username">Username</label>
<input
id="username"
type="text"
value={enteredUsername}
onChange={usernameChangeHandler}
/>
<label htmlFor="age">Age (Years)</label>
<input
id="age"
type="number"
value={enteredAge}
onChange={ageChangeHandler}
/>
<Button type="submit">Add User</Button>
</form>
</Card>
</Wrapper>
);
};
export default AddUser;
<input
id="age"
type="number"
value={enteredAge}
onChange={ageChangeHandler}
/>
const AddUser = (props) =>
{
const [enteredUsername, setEnteredUsername] = useState("");
const [enteredAge, setEnteredAge] = useState("");
const [error, setError] = useState();
<input
id="age"
type="number"
value={enteredAge}
onChange={ageChangeHandler}
/>
props.onAddUser(enteredUsername, enteredAge);
setEnteredUsername("");
setEnteredAge("");
};
๐ย ref๋ฅผ ์ฌ์ฉํ์ง ์์ ๊ฒฝ์ฐ์ form๋ง ์ ์ถํ๊ธฐ๋ง ํ๋ฉด ๋๋๋ฐ ํค ์ ๋ ฅ๋ง๋ค ์ํ๋ฅผ ์ ๋ฐ์ดํธํ๋ ๊ฑด ์ข ... ๋ถํธ์ค ํ ์์๋ค... (๊ณผํ๋ค..) ์ด๋ด ๋ ํ์ํ๊ฒ์ ?!!! ref!!!
ref๋ฅผ ์ฌ์ฉํ๋ฉด ์ฐ๊ฒฐ์ ๋ง๋ค ์ ์๋ค.
๐ย ๋ ๋๋ง ๋ HTML์์์ ์๋ฐ์คํฌ๋ฆฝํธ ์ฝ๋๊ฐ์ ์ฐ๊ฒฐ์ด ๊ฐ๋ฅ!!
๐ย useRef๊ฐ ๋ฐํํ๋ ๊ฐ์ด ์ค์!! ํ๋ค. ๋์ค์ ํ์ฉํ๊ฒ ๋๋ฉด ์ฐ๊ฒฐํ๋ ค๋ ์์์ ์์ ํ ์ ์๊ฒ ํด์ค๋ค.
์ฌ์ฉ๋ฐฉ๋ฒ
๋จผ์ , ref๋ฅผ ์ฌ์ฉํ๋ ค๋ฉด
import React, { useState, useRef } from "react";
const AddUser = (props) => {
const nameInputRef = useRef();
const ageInputRef = useRef();
const [enteredUsername, setEnteredUsername] = useState("");
const [enteredAge, setEnteredAge] = useState("");
const [error, setError] = useState();
<input
id="age"
type="number"
value={enteredAge}
onChange={ageChangeHandler}
ref={ageInputRef}
/>