프론트엔드/React

[React] 컴포넌트 props로 함수 전달하기, 다른 컴포넌트 함수 호출하기

순코딩 2024. 1. 19. 00:11

props로 함수 전달하기(매개변수x)

//부모 컴포넌트
import React from "react";
import Child from "./Child";

const Parent = () => {
  // props로 전달할 함수
  const testFunc = () => {
    console.log("addArticle 함수 호출");
  };

  return <Child propsFunc={testFunc} />;
};

export default Parent;
// 자식 컴포넌트
import React from "react";

const Child = ({ propsFunc }) => {
  return (
    <button onClick={propsFunc}> // 버튼 클릭 시 부모 컴포넌트의 testFunc 함수 호출
      Add Article
    </button>
  );
};

export default Child;

 

props로 함수 전달하기(매개변수O)

// 부모 컴포넌트
const Parent = () => {
  // props로 전달할 함수
  const testFunc = (title, content) => {
    console.log("addArticle 함수 호출");
    console.log("title:", title);
    console.log("content:", content);
  };

  // props로 전달할 매개변수
  const testTitle = "테스트제목";
  const testContent = "테스트내용";
  
  // 자식 컴포넌트 props로 함수와 매개변수를 전달한다
  return (
    <Child propsFunc={testFunc} param1={testTitle} param2={testContent}/>
  );
};
// 자식 컴포넌트
// props로 함수와 함수의 매개변수를 전달한다.
const Child = ({ propsFunc, param1, param2 }) => {
  // 버튼 클릭 시 실행할 함수
  const buttonClick = () => {
    propsFunc(param1, param2);
  };

  // 버튼 클릭 시 부모 컴포넌트의 testFunc가 실행되어 콘솔에 param1과 param2를 출력한다.
  return (
    <button onClick={buttonClick}>버튼 클릭</button>
  );
};