민프

[React][TypeScript] forwardRef를 이용하여 부모에서 자식으로 Props와 Ref들을 넘겨보자 본문

[React]

[React][TypeScript] forwardRef를 이용하여 부모에서 자식으로 Props와 Ref들을 넘겨보자

민프야 2023. 3. 9. 10:29

자식 컴포넌트

Child.tsx

import { TextField, TextFieldProps } from "@mui/material";
import React, {
  forwardRef,
  RefObject,
  useImperativeHandle,
  useRef,
} from "react";
import styled from "styled-components";
// Create your ref types here
export type CategoryRefHandler = {
  inputRef: RefObject<TextFieldProps>;
  //여기에서 정의한 Ref들은 부모에서 사용할 수 있다.
};

const CategoryInputBox = forwardRef((props: any, ref: any) => {
  const inputRef = useRef<TextFieldProps>(null);

  // Initialise your refs here
  useImperativeHandle(ref, () => ({
    inputRef,
  }));

  return (
    <Container>
      <span className="titleText">{props.props[0].title}</span>
      <InputContainer>
        <TextField
          id="outlined-basic"
          variant="outlined"
          fullWidth
          placeholder={props.props[0].placeHolder}
          inputRef={inputRef}
          color="primary"
        />
      </InputContainer>
    </Container>
  );
});

export default CategoryInputBox;

const Container = styled.div`
  .titleText {
    font-size: ${(props) => props.theme.body.fontMediumLarge};
    color: ${(props) => props.theme.body.black};
  }
`;

const InputContainer = styled.div`
  margin-top: 12px;
`;

부모 컴포넌트

import { CustomButton } from "component";
import CategoryInputBox, {
  CategoryRefHandler,
} from "pages/assetPage/component/CategoryInputBox";
import CustomDropDown from "pages/assetPage/component/CustomDropdown";
import React, { useRef } from "react";
import { useTranslation } from "react-i18next";
import styled from "styled-components";

function WithdrawInput() {
  const { t } = useTranslation("assetDeposit");

  const memoInput = useRef<CategoryRefHandler>(null);
  const memoInputProps = [
    {
      title: t("MD"),
      placeHolder: t("MDPH"),
    },
  ];


  return (
    <Container>
      <ItemBox>
        <CategoryInputBox ref={memoInput} props={memoInputProps} />
      </ItemBox>
    </Container>
  );
}

export default WithdrawInput;

const Container = styled.div``;

const ItemBox = styled.div`
  margin-top: 40px;
`;
Comments