ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [react] computed property names
    react+vue 2022. 10. 11. 13:58

    computed property names

    • 동적으로 객체의 키값을 할당한다.

    게시판 예제

    • 초기 데이터
    const [posts, setPosts] = useState([
            { id: 1, title: "제목1",content:"내용1" },
            { id: 2, title: "제목2" ,content:"내용2"},
            { id: 3, title: "제목3",content:"내용3" },
            { id: 4, title: "제목4",content:"내용4" },
            { id: 5, title: "제목5",content:"내용5" }
        ]);
    return (
            <div>
                <h1>리스트 페이지</h1> 
                <hr />
                {
                    posts.map((post) => {
                        return (
                            <StyledItemBoxDiv>
                                <div>
                                    번호:{post.id} 제목:{post.title} 내용:{post.content}
                                </div>
                                <button>삭제</button>
                                
                            </StyledItemBoxDiv>
                        );
                    })
                }
                <hr />
                <form>
                    <input type="text" placeholder='제목' id="title"  onChange={ handleForm} name = "title"/>
                    <input type="text" placeholder='내용' id="content" onChange={ handleForm}name = "content" />
                    <button type="button" onClick = {handleWrite}>저장</button>
                </form>
            </div>
        );
    

    상태 변수로 초기 데이터를 정의하고 map으로 화면에 뿌려준다.

    • 데이터 입력받기

    데이터가 상태변수로 정의되었으므로 onChange이벤트에 setPosts로 입력받은값을 상태변수로 변경해준다.

    const handleForm = (e) => {
            setPost({ ...post,[e.target.name]: e.target.value });//computed property names : 동적으로 키값 할당하기
        }
    

    여기서 computed property names라는 기법이 쓰인다.

    객체의 키값에 배열이 들어간 것을 볼 수 있는데

    이렇게 작성하면 키값에 input태그의 name값이 들어가게 된다.

    post전개 연산자를 추가하여 content와 title 누락 없이 모두 들어가게 한다.

    • 상태변수 변경하기
    const handleWrite = () => {
            post.id = posts[posts.length - 1].id + 1;
            setPosts([...posts, post]);
        }
    

    저장 버튼 클릭시 위의 함수가 실행되며 id값은 기존의 데이터의 마지막 id값에 1을 증가시킨 값이고, title과 content값은 입력받은 값으로 저장되며 list에 입력받은 데이터가 추가된다.

    'react+vue' 카테고리의 다른 글

    [react] Redux  (0) 2022.10.11
    [react] Flux  (0) 2022.10.11
    [react] 라우팅하기...4: useNavigate()  (1) 2022.10.05
    [react] 라우팅하기...3: useParams()  (0) 2022.10.05
    [react] 라우팅하기...2  (0) 2022.10.05

    댓글

Designed by Tistory.