민프
[React][TypeScript] forwardRef를 이용하여 부모에서 자식으로 Props와 Ref들을 넘겨보자 본문
자식 컴포넌트
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;
`;
'[React]' 카테고리의 다른 글
[React][Typscript] root에서 자동으로 padding Bottom이 생기는 이유가 뭘까? (2) | 2023.03.10 |
---|---|
[React][TypeScript][MUI] MUI TextField의 스타일을 변경해보자(feat: endAdorment) (0) | 2023.03.09 |
[React][TypeScript] Clipboard API 를 이용하여서 붙여넣기를 해보자 (0) | 2023.02.28 |
[React][typeScript] react-datePicker 키보드 입력 막기 (1) | 2023.02.17 |
[React][TypeScript] react-datePicker Icon과 같이 사용하기 (feat.label) (0) | 2023.02.17 |
Comments