► React Native/개발일기
[React Native] value전달 (자식 컴포넌트→부모 컴포넌트)_ex체크박스
다람트리
2023. 2. 27. 20:36
반응형
[ 부모컴포넌트 ]
- useState만들기 (value 받아와서 담을용도)
- 자식컴포넌트에서 getChkAgree 함수 props 받아오기
- 부모 컴포넌트에서 getChkAgree 함수 실행(자식컴포넌트에서 받아온 value를, 부모의 useState chkAgree 에 담기)
const 부모 = ({ }) => {
const [chkAgree, setChkAgree] = useState(false);
const getChkAgree = boolean => { setChkAgree(boolean); };
console.log(chkAgree, '<--개인정보제공동의 상태');
.....
return ( <>
.....
<자식
text={`개인 정보 제공 동의 : `}
styleLayout1={{ marginTop: 20 }}
styleTxt1={{ letterSpacing: -1 }}
getChkAgree={getChkAgree} />
</>
);
};
[자식컴포넌트]
- useState만들기 (chkAgree value 담을용도)
- useEffect 사용해서 chkAgree 바뀔때마다, 부모컴포넌트에서 실행될 함수 만들기 (getChkAgree)
const 자식 = ({
getChkAgree,
}) => {
const [chkAgree, setChkAgree] = useState(false);
// checkbox 바뀔때마다, boolean값 부모로 전달
useEffect(() => {
getChkAgree(chkAgree);
}, [chkAgree]);
const styles = StyleSheet.create({
.....
txt2: { lineHeight: 24, fontWeight: 'bold', color: chkAgree ? 'black' : 'red', },
});
return (
.....
<CheckBox
checked={chkAgree}
onChange={() => setChkAgree(!chkAgree)}
/>
<Text> {chkAgree ? ` O` : ` X`} </Text>
</Layout> );
};
const 자식 = ({
styleLayout1,
styleChkbox1,
styleTxt1,
styleTxt2,
text,
getChkAgree,
}) => {
const [chkAgree, setChkAgree] = useState(false);
// checkbox 바뀔때마다, boolean값 부모로 전달
useEffect(() => {
getChkAgree(chkAgree);
}, [chkAgree]);
const styles = StyleSheet.create({
layout1: { flexDirection: 'row' },
chkbox1: {
flexDirection: 'row',
},
txt1: {},
txt2: {
lineHeight: 24,
fontWeight: 'bold',
color: chkAgree ? 'black' : 'red',
},
});
return (
<Layout
style={{
...styles.layout1,
...styleLayout1,
}}>
<CheckBox
checked={chkAgree}
text={text}
onChange={() => setChkAgree(!chkAgree)}
style={{
...styles.chkbox1,
...styleChkbox1,
}}
textStyle={{ ...styles.txt1, ...styleTxt1 }}
/>
<Text
style={{
...styles.txt2,
...styleTxt2,
}}>
{chkAgree ? ` O` : ` X`}
</Text>
</Layout>
);
};
[결과]
개인적으로 개발시행착오를 겪으면서, 그런 경험들을 기록하기도하고, 모은정보들을 메모하며, 개인공부내용을 공유하는 게시물입니다. 친절한 조언과 다양한 의견 남겨주시고, 소통해주시는분들은 언제든지 환영합니다 :D
반응형