React, Ref, ValidationSample.jsx, 참조
2024. 12. 13. 16:46ㆍ카테고리 없음
ValidationSample.jsx
import React, { useRef, useState } from 'react';
import styled from 'styled-components';
const ValidationSample = () => {
const inputRef = useRef(); // 참조
const [password, setPassword] = useState('');
const [clicked, setClicked] = useState(false);
const [validated, setValidated] = useState(false);
const handleChange = (e) => {
setPassword(e.target.value);
};
const handleButtonClick = () => {
setClicked(true);
setValidated(password === '0000');
inputRef.current.focus(); // 참조
};
return (
<div>
<input
ref={inputRef} // 참조
type="password"
value={password}
onChange={handleChange}
className={clicked ? (validated ? 'success' : 'failure') : ''}
/>
<button onClick={handleButtonClick}>검증하기</button>
</div>
);
};
export default ValidationSample;
https://stackblitz.com/edit/react-basecamp-neh1qptw?embed=1&file=src%2FValidationSample.jsx