하위 컴포넌트가 상위 컴포넌트로 값을 전달하는 방법

onezerokang·2021년 7월 5일
7
post-thumbnail

React를 사용하다보면 상위 컴포넌트에서 하위 컴포넌트로 값을 넘겨줄 때가 많다. 그럴 때 보통 props를 사용한다. 하지만 하위 컴포넌트에서 상위 컴포넌트로 값을 넘겨줄 때는 props로 넘겨줄 수가 없다. 이럴 때 어떻게 하는지에 대해 작성해보았다.

결론부터 말하면 상위 컴포넌트에서 하위컴포넌트로 함수를 props로 넘겨준다. 이후 하위 컴포넌트에서 넘겨받은 함수의 인자로 넘기고 싶은 값을 넘겨준다. 그럼 상위 컴포넌트에서 넘겨준 함수로 값을 처리할 수 있다.

다음은 예제 코드다

상위 컴포넌트

import React from "react";
import LowComponent form './LowComponent'

const HighComponent = () => {
  const highFunction = (text) => {
    console.log(text);
  }
  return (
    <LowComponent propFunction={highFunction}/>
  )
}

하위 컴포넌트

import React, { useState } from "react";

const LowComponent = (props) => {
  const [text, setText] = useState("");
  
  const textChangeHandler(e) => {
    setText(e.currentTarget.value);
  }
  
  const submitText = () => {
    props.propFunction(text)
  }
  
  return (
    <input value={text} onChange={textChangeHandler}/>
    <button onClick={submitText}>submit</button>
  )
}

export default LowComponent
profile
블로그 이전 했습니다: https://techpedia.tistory.com

0개의 댓글