코딩 기록/react
react / useEffect 써서 버튼 누를때 특정 텍스트 화면에 보이게 하기 / typescript
NomadHaven
2022. 3. 8. 23:38
실행문
npx react-native init sample20 --template react-native-template-typescript
App.tsx
import React, { useEffect, useState } from "react";
import { Button, Text, View } from "react-native";
/*
useEffect: 컴퍼넌트가 rendering 될때마다 특정 작업을 실행할 수 있도록 하는 hook
compoentDidMount + componentDidUpdate + componentWillUnmount
*/
function Welcome(props:any) {
console.log('start')
useEffect(()=>{ //==$(document).ready()
props.setText('My World')
console.log('useEffect')
})
console.log('end')
function func(){
props.setText('world')
}
return(
<View>
<Text>Welcome</Text>
<Button title="button" onPress={func}></Button>
</View>
)
}
export default function App(){
//get set
const [text,setText] =useState('abc')
return(
<View>
<Text>hello {text}</Text>
<Welcome setText={setText}/>
</View>
)
}
버튼 누르면 Hello My World 라는 텍스트가 보인가

Welcome 함수 안에 있는 uesEffect로 인해 text는 My World로 세팅되고 콘솔에 useEffect가 출력되었다.
