Posts React Hooks - useRef()
Post
Cancel

React Hooks - useRef()

zeroCho님의 nodebird강좌를 복습하는 중 imageInput과 postInput에서 왜 useRef()를 사용하는지 궁금해졌다

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
const PostForm = ({ post }) => {


    const imageInput = useRef();
    const postInput = useRef();
    const onClickImageUpload = useCallback(() => {
        imageInput.current.click();
    }, [imageInput.current]);

 
    useEffect(() => {
        if (updatePostDone) {
            postInput.current.value();
        }
    }, [updatePostDone]);
	
  
    return (
        <Form
            style=
            encType="multipart/form-data"
            onFinish={onSubmit}>
            <Input.TextArea value={text} onChange={onChangeText} maxLength={140} placeholder="어떤 일이 있었나요?" />
            <div>
                <input type="file" name="image" multiple hidden ref={imageInput} onChange={onChangeImages} />
                <Button onClick={onClickImageUpload}>upload image</Button>
                <Button type="primary" style= htmlType="submit">twit</Button>
            </div>
           
        </Form>
    );
};
export default PostForm;

useRef란

React를 사용하다보면, 컴포넌트의 메소드에서 컴포넌트의 태그에 직접 접근하고 싶을 때 사용하는 게 ref 속성 리렌더링과 관련없이 한 번 만들어진 컴포넌트에서 이전 데이터를 유지하고 싶다면 useRef() useState()는 화면 렌더링과 관련된 데이터를 저장하는 공간이여서 state를 바꾸면 컴포넌트가 리렌더링되고 맙니다 useRef로 생성한 데이터는 리렌더링 여부와 상관없이 같은 값이 유지됩니다. 또한 그 값을 바꾸더라도 화면이 리렌더링되지 않습니다.

출처:zeroCho blog https://www.zerocho.com/category/React/post/5f9a7c8807be1d0004347311

This post is licensed under CC BY 4.0 by the author.

React Hooks - useEffect()

일치연산자(===)와 동등연산자(==)

Comments powered by Disqus.