2022. 1. 8. 13:25ㆍReact Native/Basic


1. React란
User Interface 를 개발하기 위한 JS library
텍스트, 버튼, 그림 같은 화면을 구성하는 뷰를 만들어주는 라이브러리.
페이스북에서 개발하고 관리 중이다.
2. 화면 출력 맛보기
react 모듈에서 Component 클래스 import.
Component 클래스를 App이라는 클래스가 상속받는데, 이 안에는 render() 라는 함수가 있고, 이 함수가 리턴하는 것들이 화면을 구성하게 된다.
import React, { Component } from 'react';
import { View, Text, StyleSheet } from 'react-native';
class App extends Component {
render() {
return (
<View style={styles.background}>
<Text> Hello World </Text>
</View>
)
}
}
const styles = StyleSheet.create({
background: {
flex: 1,
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center'
}
})
export defualt App;
3. State
state는 컴포넌트에서 렌더링되는 데이터를 담고 유지관리하는 자바스크립트 객체.
state에 따라 화면에 보여지는 값이 달라진다.
state는 클래스 컴포넌트 안에서 사용 가능하고, 함수형 컴포넌트를 정의했다면 state 사용이 불가능하다.
// 함수형 컴포넌트
const App = () => {
return {
}
}
//클래스 컴포넌트
class App extends Component {
render() {
return (
)
}
}
state는 render 함수 바깥에서 정의된다.
import React, { Component } from 'react';
import { View, Text, StyleSheet } from 'react-native';
class App extends Component {
state = {
sampleText: 'Hello World'
}
render() {
return (
<View style={styles.background}>
<Text> {this.state.sampleText} </Text>
</View>
)
}
}
const styles = StyleSheet.create({
background: {
flex: 1,
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center'
}
})
export defualt App;
직접 입력하는 것과 텍스트를 변수에 할당해서 그 값을 출력하는 것과는 큰 차이가 있다.
결과는 같을지 몰라도 데이터 재사용성, 값 수정의 용이성의 이유로 훨씬 효율적이고 합리적이다.
+) this.state. 에서 this는 JS 문법으로 상위 스코프를 가리킴.
import React, { Component } from 'react';
import { View, Text, StyleSheet } from 'react-native';
class App extends Component {
state = {
sampleText: 'Hello World'
sampleBoolean: false
}
inputText = () => {
this.state.sampleBoolean ?
<Text>sampleBoolean is true</Text>
:
<Text>sampleBoolean is false</Text>
}
render() {
return (
<View style={styles.background}>
{this.inputText()}
</View>
)
}
}
const styles = StyleSheet.create({
background: {
flex: 1,
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center'
}
})
export defualt App;
state는 화면을 렌더링할 때 쓰이는 데이터를 관리할 때 쓰는 객체로 값에 따라 상이한 화면이 출력된다.
4. setState
state 값을 바꿔주는 방법.
state는 직접 변경하면 안 되는 특성을 가진다.
import React, { Component } from 'react';
import { View, Text, StyleSheet } from 'react-native';
class App extends Component {
state = {
sampleText: 'Hello World'
sampleBoolean: false
}
inputText = () => {
this.state.sampleText: 'Hi World' // 잘못된 state 변경.
this.state.sampleBoolean ?
<Text>sampleBoolean is true</Text>
:
<Text>sampleBoolean is false</Text>
}
render() {
return (
<View style={styles.background}>
{this.inputText()}
</View>
)
}
}
const styles = StyleSheet.create({
background: {
flex: 1,
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center'
}
})
export defualt App;
위 코드와 같이 변경하게 되면 화면에 다시 렌더링하지 않기 때문에 변경된 값이 화면에 반영되지 않는다. 따라서 state를 직접 바꾸는 게 아니라 setState라는 메소드를 이용해야 한다.
setState로 state를 변경해야만 state 값이 갱신될 때 화면을 다시 렌더링해서 반영시킬 수 있다.
state는 렌더링되는 데이터를 관리하기 때문에 일부러 직접 변경될 수 없어야 하는 특성을 갖게 만든 것이다.
import React, { Component } from 'react';
import { View, Text, StyleSheet } from 'react-native';
class App extends Component {
state = {
sampleText: 'Hello World'
sampleBoolean: false
}
inputText = () => {
this.state.sampleBoolean ?
<Text>sampleBoolean is true</Text>
:
<Text>sampleBoolean is false</Text>
}
chageState = () => {
if (this.state.sampleBoolean) {
this.setState({
sampleText: 'Text Changed!!!',
sampleBoolean: true
})
} else {
this.setState({
sampleText: 'Hello World!!!',
sampleBoolean: false
})
}
}
render() {
return (
<View style={styles.background}>
<Text onPress={this.changeState}>
{this.state.sampleText}
</Text>
</View>
)
}
}
const styles = StyleSheet.create({
background: {
flex: 1,
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center'
}
})
export defualt App;
버튼을 눌렀을 때 반응하는 액션을 event라고 한다. 버튼 뿐 아니라 텍스트가 클릭되었을 때도 이벤트를 발생시킬 수 있다.
Hello World 라는 글자를 클릭했을 때 changeState라는 메소드가 호출되고 setState를 통해 sampleText의 값을 변경한다.
비동기성
state는 조심히 다뤄야할 객체라 성능 향상을 위해 단일 업데이트를 지원한다. setState를 통한 데이터의 값을 변경할 때는 현재 버전을 복사한 다음 업데이트를 진행한다.
아래 코드에서는 단순히 sampleNum = sampleNum + 1 로 작성한 경우로 에러가 발생하게 된다.
import React, { Component } from 'react';
import { View, Text, StyleSheet } from 'react-native';
class App extends Component {
state = {
sampleText: 'Hello World'
sampleBoolean: false
sampleNum: 1
}
inputText = () => {
this.state.sampleBoolean ?
<Text>sampleBoolean is true</Text>
:
<Text>sampleBoolean is false</Text>
}
chageState = () => {
if (this.state.sampleBoolean) {
this.setState({
sampleText: 'Text Changed!!!',
sampleBoolean: true
})
} else {
this.setState({
sampleText: 'Hello World!!!',
sampleBoolean: false
})
}
}
odAdd = () => {
this.setState({
//sampleNum: sampleNum + 1 // 에러 발생
sampleNum: 100
})
}
render() {
return (
<View style={styles.background}>
<Text onPress={this.onAdd}>
{this.state.sampleNum}
</Text>
</View>
)
}
}
const styles = StyleSheet.create({
background: {
flex: 1,
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center'
}
})
export defualt App;
에러가 나지 않도록 state 값을 변경하기 위해서는 prevState를 이용하여 값을 변경하여 주면 된다.
import React, { Component } from 'react';
import { View, Text, StyleSheet } from 'react-native';
class App extends Component {
state = {
sampleText: 'Hello World'
sampleBoolean: false
sampleNum: 1
}
inputText = () => {
this.state.sampleBoolean ?
<Text>sampleBoolean is true</Text>
:
<Text>sampleBoolean is false</Text>
}
chageState = () => {
if (this.state.sampleBoolean) {
this.setState({
sampleText: 'Text Changed!!!',
sampleBoolean: true
})
} else {
this.setState({
sampleText: 'Hello World!!!',
sampleBoolean: false
})
}
}
odAdd = () => {
this.setState(prevState => {
return {
sampleNum: prevState.samplemNum + 1
})
}
render() {
return (
<View style={styles.background}>
<Text onPress={this.onAdd}>
{this.state.sampleNum}
</Text>
</View>
)
}
}
const styles = StyleSheet.create({
background: {
flex: 1,
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center'
}
})
export defualt App;
5. Props
props는 read only로 수정, 변경이 불가능한 읽기 전용 프로퍼티이다. 리액트나 리액트 네이티브나 데이터의 흐름을 보면 일방 통행이다. 부모로부터 자식한테 데이터가 전해진다. 자식 컴포넌트는 부모로부터 props라는 데이터를 받고, 그 값은 자식 컴포넌트 내에서 수정, 변경 되지 않고 그대로 사용하게 된다.
props를 쓰는 이유는 뭘까?
부모에게 여러 자식이 있고 모든 자식에게 편지를 쓴다고 한다. 1~100번째의 자식에게 똑같은 편지를 쓴다고 하면 굉장히 비효율적이다. 부모는 편지 원본을 가지고 100명의 자식에게 복사본이 전달되면 보다 효율적이게 된다.
react props 개념상 복사본은 부적절할 수 있지만 부모가 가진 정보가 완전히 똑같이 모든 자식에게 간편하고 손쉽게 전달될 수 있다는 것이 중요하다. 부모가 자신이 가진 정보를 자식에게 전달하는 수단으로 react가 사용하는 방법이 props.
import React from 'react';
import { View, Text } from 'react-native';
const PropsChild = (props) => {
return (
<View>
<Text onPress={props.cState}>
{props.sText}
</Text>
</View>
)
}
export default PropsChild;
import React, { Component } from 'react';
import { View, Text, StyleSheet } from 'react-native';
import PropsChild from './propsChild'
class App extends Component {
state = {
sampleText: 'Hello World'
sampleBoolean: false
sampleNum: 1
}
inputText = () => {
this.state.sampleBoolean ?
<Text>sampleBoolean is true</Text>
:
<Text>sampleBoolean is false</Text>
}
chageState = () => {
if (this.state.sampleBoolean) {
this.setState({
sampleText: 'Text Changed!!!',
sampleBoolean: true
})
} else {
this.setState({
sampleText: 'Hello World!!!',
sampleBoolean: false
})
}
}
odAdd = () => {
this.setState(prevState => {
return {
sampleNum: prevState.samplemNum + 1
})
}
render() {
return (
<View style={styles.background}>
<PropsChild sText={this.state.sampleText} cState={this.changeState}/>
</View>
)
}
}
const styles = StyleSheet.create({
background: {
flex: 1,
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center'
}
})
export defualt App;
자식이 부모의 데이터를 받아서 자유롭게 활용 가능한 것도 props의 큰 장점이다.
참고 자료
iOS/Android 앱 개발을 위한 실전 React Native - Basic - 인프런 | 강의
Mobile App Front-End 개발을 위한 React Native의 기초 지식 습득을 목표로 하고 있습니다. 진입장벽이 낮은 언어/API의 활용을 통해 비전문가도 쉽게 Native Mobile App을 개발할 수 있도록 제작된 강의입니다
www.inflearn.com
'React Native > Basic' 카테고리의 다른 글
[React Native] React Native Component - 2. View, Text (0) | 2022.01.12 |
---|---|
[React Native] React Native Component - 1. Intro (0) | 2022.01.11 |
[React Native] ECMAScript 6 (ES6) (0) | 2022.01.06 |
[React Native] error/solution (0) | 2022.01.05 |
[React Native] React Native 소개 및 개발 환경 구축 (0) | 2021.12.29 |