반응형

 

flex

import React from 'react';
import { StyleSheet, View, Text } from 'react-native';

export const Header = () => {
    return (
        <View style = {[styles.container, styles.header]}>
            <Text style={styles.text}>Header</Text>
        </View>
    );
};

export const Contents = () => {
    return (
        <View style={[styles.container, styles.contents]}>
            <Text style={styles.text}>Contents</Text>
        </View>
    );
};

export const Footer = () => {
    return (
        <View style ={[styles.container, styles.footer]}>
            <Text style={styles.text}>Footer</Text>
        </View>
    );
};




const styles = StyleSheet.create({
    container: {
        width: '100%',
        alignItems: 'center',
        justifyContent: 'center',
        height: 80,
    }, => contents와 text의 height는 80으로 고정

    header: {
        backgroundColor: '#f1c40f',
        height: 640,
    }, => header의 height는 640
    contents: {
        backgroundColor: '#3498db',
    },
    text: {
        fontSize: 26,
    },
});

=> 아이폰 11에서는 잘리지 않고 다 보이지만 에뮬레이터에선 잘려보인다.

 

flex를 이용하면 width, height와 달리 비율로 크기가 결정된다.

-flex의 값이 0일때는 설정된 width와 heigth값에 따라 크기가 결정

-양수일 경우 felx값에 비례하여 크기가 조정

ex)

(위의 코드에서 footer를 추가하는 것을 깜빡하였다.)

import React from 'react';
import { StyleSheet, View, Text } from 'react-native';

export const Header = () => {
    return (
        <View style = {[styles.container, styles.header]}>
            <Text style={styles.text}>Header</Text>
        </View>
    );
};

export const Contents = () => {
    return (
        <View style={[styles.container, styles.contents]}>
            <Text style={styles.text}>Contents</Text>
        </View>
    );
};

export const Footer = () => {
    return (
        <View style ={[styles.container, styles.footer]}>
            <Text style={styles.text}>Footer</Text>
        </View>
    );
};

const styles = StyleSheet.create({
    container: {
        width: '100%',
        alignItems: 'center',
        justifyContent: 'center',
        height: 80,
    },

    header: {
        flex: 1,
        backgroundColor: '#f1c40f',
        height: 640,
    },
    contents: {
        flex: 2,
        backgroundColor: '#3498db',
    },
    => 추가
    footer: {
        flex: 1,
        backgroundColor: '#1abc9c',
    },

    text: {
        flex: 3,
        fontSize: 26,
    },
});

1:2:1 비율로 나누어 채워지게 된다.

 

 

정렬

컴포넌트가 쌓이는 방향

- flexDirection사용

 

 

- justiftContent

 

flex-start : 시작점에서부터 정렬 (기본값)

flex-end : 끝에서부터 정렬

center : 중앙 정렬

space-between : 컴포넌트 사이의 공간을 동일하게 만들어서 정렬

space-around : 컴포넌트 각가의 주변 공간을 동일하게 만들어서 정렬

space-evenly : 컴포넌트 사이와 양 끝에 동일한 공간을 만들어서 정렬

 

- alignItems

 

flex-start : 시작점에서부터 정렬 (기본값)

flex-end : 끝에서부터 정렬

center : 중앙정렬

strecth : alignItems의 방향으로 컴포넌트 확장

baseline :  컴포넌트 내부의 텍스트 베이스라인을 기준으로 정렬

728x90
반응형

'공부 > 리액트 네이티브' 카테고리의 다른 글

스타일링  (0) 2021.05.08
리액트 네이티브 - 이벤트  (0) 2021.05.06
리액트 네이티브 - props  (0) 2021.05.06
리액트 네이티브 - props  (0) 2021.05.06
리액트 네이티브 - button 컴포넌트  (0) 2021.05.06
블로그 이미지

아상관없어

,
반응형

JSX는 backgroundColor와 같이 카멜 표기법으로 작성해야한다.

 

expo init react-native-style

./src/App.js 생성

 

 

인라인 스타일링

컴포넌트에 직접 스타일을 입력하는 방식

객체 형태로 전달

import React from 'react';
import { View, Text } from 'react-native';

const App = () => {
    return (
        <View
            style={{
                flex: 1,
                backgroundColor: '#fff',
                alignItems: 'center',
                justifyContent: 'center',
            }}
        >
            <Text
                style={{
                    padding: 10,
                    fontSize: 26,
                    fontWeight: '600',
                    color: 'black',
                }}
            >
                Inline Styling - Text 
            </Text>
            
            <Text
                style ={{
                    padding: 10,
                    fontSize: 26,
                    fontWeight: '400',
                    color: 'red',
                }}
            >
                Inline Styling - Error               
            </Text>
        </View>
    );
};

export default App;

 

 

명확하게 어떤 스타일인지 보이지만,

비슷한 역할을 하는 컴포넌트에 동일한 코드가 반복되고,

어떤 이유로 해당 스타일이 적용되었는지 가늠하기 힘듬

 

 클래스 스타일링

컴포넌트의 태그에 직접 입력 X

스타일 시트에 정의된 스타일을 사용

import React from 'react';
import { StyleSheet, View, Text } from 'react-native';

const App = () => {
    return (
        <View style = {styles.container}>
            <Text style = {styles.text}> Text </Text>
            <Text style = {styles.error}> Error </Text>
        </View>
    );
};


const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: '#fff',
        alignItems: 'center',
        justifyContent: 'center',
    },
=> padding, fontsize, fontweight, color를 지정한 이유를 보여줌
(예를 들어 색을 바꿀 때 text객체의 color만 바꾸어주면 되어 편함)
    text: {
        padding: 10,
        fontSize: 26,
        fontweight: '600',
        color: 'black',
    },
=> padding, fontsize, fontweight, color를 지정한 이유를 보여줌
    error: {
        padding: 10,
        fontSize: 26,
        fontWeight: '400',
        color: 'red',
    },

});


export default App;

 

여러개 스타일 적용

위의 text와 error는 중복된 스타일이 많음.

두 스타일 모두 Text 컴포넌트에 적용되는 스타일임

배열을 이용하여 여러 개의 스타일 적용

mport React from 'react';
import { StyleSheet, View, Text } from 'react-native';

const App = () => {
    return (
        <View style = {styles.container}>
            <Text style = {styles.text}> Text </Text>
            => 뒤에 오는 스타일이 앞에 있는 스타일을 덮음
            <Text style = {[styles.text,styles.error]}> Error </Text>
        </View>
    );
};


const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: '#fff',
        alignItems: 'center',
        justifyContent: 'center',
    },

    text: {
        padding: 10,
        fontSize: 26,
        fontweight: '600',
        color: 'black',
    },

    error: {
        fontWeight: '400',
        color: 'red',
    },

});


export default App;

 

 

 

상황에 따라 인라인, 클래스 스타일 방식 혼용

import React from 'react';
import { StyleSheet, View, Text } from 'react-native';

const App = () => {
    return (
        <View style = {styles.container}>
            <Text style = {[styles.tex, { color: 'green'}]}> Text </Text> <= 배열사용, 혼용
            <Text style = {[styles.text,styles.error]}> Error </Text>
        </View>
    );
};


const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: '#fff',
        alignItems: 'center',
        justifyContent: 'center',
    },

    text: {
        padding: 10,
        fontSize: 26,
        fontWeight: '600',
        color: 'black',
    },

    error: {
        fontWeight: '400',
        color: 'red',
    },

});


export default App;

 

 

 

 

 

 

외부 스타일 사용

만든 스타일을 다양한 곳에서 사용가능

외부 파일에 스타일을 정의하고 여러개의 파일에서 스타일을 공통으로 사용

./src/styles.js 생성

import {StyleSheet} from 'react-native';

export const viewStyles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: '#fff',
        alignItems: 'center',
        justifyContent: 'center',
    },
});

export const textStyles = StyleSheet.create({
    text: {
        padding: 10,
        fontSize: 26,
        fontWeight: '600',
        color: 'black',
    },

    error: {
        fontWeight: '400',
        color: 'red',
    },
});

//App.js


import React from 'react';
import { View, Text } from 'react-native';
import { viewStyles, textStyles } from './styles'; => ./styles에서 viewStyles, textStyles 가져옴


const App = () => {
    return (
        <View style = {viewStyles.container}>
            <Text style = {[textStyles.text, { color: 'green'}]}> Text </Text>
            <Text style = {[textStyles.text,textStyles.error]}> Error </Text>
        </View>
    );
};




export default App;

 

728x90
반응형

'공부 > 리액트 네이티브' 카테고리의 다른 글

스타일 속성  (0) 2021.05.09
리액트 네이티브 - 이벤트  (0) 2021.05.06
리액트 네이티브 - props  (0) 2021.05.06
리액트 네이티브 - props  (0) 2021.05.06
리액트 네이티브 - button 컴포넌트  (0) 2021.05.06
블로그 이미지

아상관없어

,
반응형

press 이벤트

onClick 과 비슷한 이벤트

TouchableOpacity 컴포넌트에서 설정할 수 있는 Press 이벤트의 종류는 4가지임

onPressIn : 터치가 시작될때 항상 호출

onPressOut : 터치가 해제될 때 항상 호출

onPress : 터치가 해제될때 onPressOut 이후 호출

onLongPress : 터치가 일정 시간 이상 지속되면 호출

import React from 'react';
import { TouchableOpacity, Text } from 'react-native'

const EventButton = () => {
    const _onPressIn = () => console.log('Press In!!\n');
    const _onPressOut = () => console.log('Press Out!!\n');
    const _onPress = () => console.log('Press !!\n');
    const _onLongPress = () => console.log('Long Press !!\n');


    return (
        <TouchableOpacity
            sytle={{
                backgroundCloer: '#f1c40f',
                padding: 16,
                margin: 10,
                borderRadius: 8,
            }}

            onPressIn={_onPressIn}
            onLongPress={_onLongPress}
            onPressOut={_onPressOut}
            onPress={_onPress}
        >
            <Text style={{color: 'white', fontSize: 24}}>Press</Text>
        </TouchableOpacity>
    );
};

export default EventButton;
import React from 'react';
import {View} from 'react-native';
import EventButton from './components/EventButton';

const App = () => {
    return (
        <View
            style={{
                flex: 1,
                backgroundColor: '#fff',
                alignItems: 'center',
                justifyContent: 'center',
            }}
        >
            <EventButton /> 

        </View>
    );
};


export default App;

 

 

change 이벤트

change는 값을 입력하는 TextInput 컴포넌트에서 많이 사용된다.

import React, { useState } from 'react';
import { View, Text, TextInput } from 'react-native';

const EventInput = () => {
    const [text, setText] = useState('');
    const _onChange = event => setText(event.nativeEvent.text);
    return(
        <View>
            <Text style = {{ margin: 10, fontSize: 30}}>text: {text}</Text>
            <TextInput
                style={{ borderWidth: 1, padding: 10, fontSize: 20}}
                onChange={_onChange}
            />
        </View>
    );
};

export default EventInput;

TextInput 

import React from 'react';
import {View} from 'react-native';
import EventButton from './components/EventButton';
import EventInput from './components/EventInput';

const App = () => {
    return (
        <View
            style={{
                flex: 1,
                backgroundColor: '#fff',
                alignItems: 'center',
                justifyContent: 'center',
            }}
        >

            <EventInput />

        </View>
    );
};


export default App;

 

 

 

728x90
반응형

'공부 > 리액트 네이티브' 카테고리의 다른 글

스타일 속성  (0) 2021.05.09
스타일링  (0) 2021.05.08
리액트 네이티브 - props  (0) 2021.05.06
리액트 네이티브 - props  (0) 2021.05.06
리액트 네이티브 - button 컴포넌트  (0) 2021.05.06
블로그 이미지

아상관없어

,
반응형

props : properties의 줄임마로, 부모 컴포넌트로부터 전달된 속성값 또는 상속받은 속성값을 말함.

부모 컴포넌트에서 자식 컴포넌트의 props를 설정하면 자식 컴포넌트에서는 해당 props를 사용할 수 있고, 수정은 부모 컴포넌트에서만 가능하다.

 

props 전달, 사용

App.js

import React from 'react';
import {Text, View} from 'react-native';
import MyButton from './components/MyButton';

const App = () => {
    return (
        <View
            style={{
                flex: 1,
                backgroundColor: '#fff',
                alignItems: 'center',
                justifyContent: 'center',
            }}
        >        
            <Text
                style={{
                    fontSize: 30,
                    marginBottom: 10,
                }}
            >
                Props
            </Text>
            //App컴포넌트에서 MyButton 컴포넌트를 호출할 때 title 속성에 Button이라는 문자열을 전달
            <MyButton title='Button' /> 
        </View>
    );
};

export default App;

MyButton.js

//리액트를 불러와서 사용할 수 있게 해줌(JSX는 React.createElement를 호출 하는 코드로 컴파일 되므로 반드시 작성)
import React from 'react';
//리액트 네이티브에서 제공되는 Pressable, Text 컴포넌트 추가
import{TouchableOpacity, Text} from 'react-native';

//Pressable 컴포넌틀르 사용해서 클릭에 대해 상호작용 할 수 있도록함.
//버튼에 내용표시하기위해 text컴포넌트 사용
//MyButton에서 부모로부터 전달된 props를 함수의 파라미터로 받음
const MyButton = props => {
	/*
    	console.log(porps);
        결과:
        Object { "title": "Button", }
    */
    return (
        <TouchableOpacity
            style={{
                backgroundColor: '#3498db',
                padding: 16,
                margin: 10,
                borderRaduis: 8,
            }}
            onPress={() => alert('click')}
        >
        	//props.title로 title값 읽어서 출력
            <Text style={{color: 'white', fotSize: 24}}>{props.title}</Text>
        </TouchableOpacity>
    );
};

export default MyButton;

MyButton의 이름이 props.title로 읽어들여 Button으로 되었다.

 

컴포넌트의 태그 사이에 값을 입력하여 전달할 수도 있다.

App.js
===============================================================
import React from 'react';
import {Text, View} from 'react-native';
import MyButton from './components/MyButton';

const App = () => {
    return (
        <View
            style={{
                flex: 1,
                backgroundColor: '#fff',
                alignItems: 'center',
                justifyContent: 'center',
            }}
        >        
            <Text style={{ fontSize: 30, marginBottom: 10, }}>
                Props
            </Text>
            <MyButton title="Button" /> 
            <MyButton title="Button">Children Props</MyButton> =>태그사이에 전달된 값은 자식 컴포넌트의 props의 children으로 전달됨
        </View>
    );
};

export default App;



MyButton.js
===============================================================
//리액트를 불러와서 사용할 수 있게 해줌(JSX는 React.createElement를 호출 하는 코드로 컴파일 되므로 반드시 작성)
import React from 'react';
//리액트 네이티브에서 제공되는 Pressable, Text 컴포넌트 추가
import{TouchableOpacity, Text} from 'react-native';

//Pressable 컴포넌틀르 사용해서 클릭에 대해 상호작용 할 수 있도록함.
//버튼에 내용표시하기위해 text컴포넌트 사용
const MyButton = props => {
    return (
        <TouchableOpacity
            style={{
                backgroundColor: '#3498db',
                padding: 16,
                margin: 10,
                borderRaduis: 8,
            }}
            onPress={() => alert('click')}
        >
            <Text style={{color: 'white', fotSize: 24}}>
                {props.children || props.title}
                </Text>
        </TouchableOpacity>
    );
};

export default MyButton;



props에 children이 있다면 title보다 우선시 되도록 작성

 

 

defaultProps

App.js에

버튼을 추가하고 아무런 값을 넘겨주지 않으면

<MyButton />

아무 표시가 되지 않는다. 

이러한 일을 방지하기 위해(반드시 전달되어야하는 값이 전달되게 설정)

MyButton.js에

MyButton.defaultProps = {

    title: 'Button',

};

를 추가하면 

MyButton 컴포넌트의 defaultProps 덕분에 기본으로 설정한 Button이 전달되었다.

 

 

 

 

propTypes

컴포넌트에 props를 전달할 때 잘못된 타입을 전달하거나, 필수로 전달해야하는 값을 전달하지 않았을 때

잘못된 props가 전달되었다고 경고하는 방법

컴포넌트에서 전달받아야하는 props의 타입과 필수 여부를 지정할 수 있음

 "npm install prop-types"

MyButton.js

MyButton.propTypes = {
	title: PropTypes.number,
};

title에 전달되어야 하는 값이 number라고 지정함

따라서 이전과 같이 String을 전달할 시 경고 메시지가 나타난다.

 

필수전달여부 => 선언된 타입 뒤에 isRequired만 붙여주면 된다.

MyButton.js

MyButton.propTypes = {
	title: PropTypes.string.isRequired,
    	name: PropTypes.string.isREquired,
};

App.js 에서 name을 전달해주지 않았으므로 에러가 발생하게 된다.

 

함수, 객체, 배열 등의 다양한 타입도 지정할 수 있다.

ex) onPress 필수로 지정

MyButton.js

MyButton.propTypes = {
	title: PropTypes.string.isRequired,
    	onPress: PropTypes.func.isRequired,
};
App.js

...
	    <MyButton title="Button" onPress={()=> alert("Click)}/> 
            <MyButton title="Button onPress={()=> alert("Click)}">
            	Children Props
            </MyButton> 
            <MyButton onPress={()=> alert("Click)}/>
....

 

 

 

 

useState

-State

컴포넌트 내부에서 생성되고 값을 변경할 수 있다.

이를 이용하여 컴포넌트 상태를 관리한다.

state : 컴포넌트에서 변화할 수 있는 값 ( 상태가 변하면 컴포넌트는 리렌더링 된다.)

 

 

useState는 상태를 관리하는 변수, 그 변수를 변경할 수 있는 setter 함수를 배열로 반환한다.

const [state, setState] = useState(initialState);

상태변수 state는 useState 함수에서 반환한 setter함수를 이용하여 변경하여야한다.

호출시 파라미터로 상태의 초기값을 전달한다.

(초기값을 전달하지 않으면 undefined로 설정되어 에러가 발생)

 

./src/component/Counter.js

import React, {useState} from 'react';
import { View, Text } from 'react-native';
import MyButton from './MyButton';

const Counter = () => {
    const [count, setCount] = useState(0);
    return (
        <View style={{ alignItems: 'center'}}>
            <Text style={{fontSize: 30, margin: 10}}>{count}</Text>
            <MyButton title = '+1' onPress={() => setCount(count + 1)} />
            <MyButton title = "-1" onPress={() => setCount(count - 1)} />
        </View>
    )
}

 

import React from 'react';
import {View} from 'react-native';
import Counter from './components/Counter';

const App = () => {
    return (
        <View
            style={{
                flex: 1,
                backgroundColor: '#fff',
                alignItems: 'center',
                justifyContent: 'center',
            }}
        >        
            <Text style={{ fontSize: 30, marginBottom: 10, }}>
                Props
            </Text>
            <MyButton title="Button" /> 
            <MyButton title="Button">Children Props</MyButton> 
            <MyButton />

            <counter /> <=counter 컴포넌트 추가

        </View>
    );
};


export default App;

 

 

728x90
반응형

'공부 > 리액트 네이티브' 카테고리의 다른 글

스타일링  (0) 2021.05.08
리액트 네이티브 - 이벤트  (0) 2021.05.06
리액트 네이티브 - props  (0) 2021.05.06
리액트 네이티브 - button 컴포넌트  (0) 2021.05.06
리액트 네이티브 - jsx  (0) 2021.05.06
블로그 이미지

아상관없어

,
반응형

props : properties의 줄임마로, 부모 컴포넌트로부터 전달된 속성값 또는 상속받은 속성값을 말함.

부모 컴포넌트에서 자식 컴포넌트의 props를 설정하면 자식 컴포넌트에서는 해당 props를 사용할 수 있고, 수정은 부모 컴포넌트에서만 가능하다.

 

props 전달, 사용

App.js

import React from 'react';
import {Text, View} from 'react-native';
import MyButton from './components/MyButton';

const App = () => {
    return (
        <View
            style={{
                flex: 1,
                backgroundColor: '#fff',
                alignItems: 'center',
                justifyContent: 'center',
            }}
        >        
            <Text
                style={{
                    fontSize: 30,
                    marginBottom: 10,
                }}
            >
                Props
            </Text>
            //App컴포넌트에서 MyButton 컴포넌트를 호출할 때 title 속성에 Button이라는 문자열을 전달
            <MyButton title='Button' /> 
        </View>
    );
};

export default App;

MyButton.js

//리액트를 불러와서 사용할 수 있게 해줌(JSX는 React.createElement를 호출 하는 코드로 컴파일 되므로 반드시 작성)
import React from 'react';
//리액트 네이티브에서 제공되는 Pressable, Text 컴포넌트 추가
import{TouchableOpacity, Text} from 'react-native';

//Pressable 컴포넌틀르 사용해서 클릭에 대해 상호작용 할 수 있도록함.
//버튼에 내용표시하기위해 text컴포넌트 사용
//MyButton에서 부모로부터 전달된 props를 함수의 파라미터로 받음
const MyButton = props => {
	/*
    	console.log(porps);
        결과:
        Object { "title": "Button", }
    */
    return (
        <TouchableOpacity
            style={{
                backgroundColor: '#3498db',
                padding: 16,
                margin: 10,
                borderRaduis: 8,
            }}
            onPress={() => alert('click')}
        >
        	//props.title로 title값 읽어서 출력
            <Text style={{color: 'white', fotSize: 24}}>{props.title}</Text>
        </TouchableOpacity>
    );
};

export default MyButton;

MyButton의 이름이 props.title로 읽어들여 Button으로 되었다.

 

컴포넌트의 태그 사이에 값을 입력하여 전달할 수도 있다.

App.js
===============================================================
import React from 'react';
import {Text, View} from 'react-native';
import MyButton from './components/MyButton';

const App = () => {
    return (
        <View
            style={{
                flex: 1,
                backgroundColor: '#fff',
                alignItems: 'center',
                justifyContent: 'center',
            }}
        >        
            <Text style={{ fontSize: 30, marginBottom: 10, }}>
                Props
            </Text>
            <MyButton title="Button" /> 
            <MyButton title="Button">Children Props</MyButton> =>태그사이에 전달된 값은 자식 컴포넌트의 props의 children으로 전달됨
        </View>
    );
};

export default App;



MyButton.js
===============================================================
//리액트를 불러와서 사용할 수 있게 해줌(JSX는 React.createElement를 호출 하는 코드로 컴파일 되므로 반드시 작성)
import React from 'react';
//리액트 네이티브에서 제공되는 Pressable, Text 컴포넌트 추가
import{TouchableOpacity, Text} from 'react-native';

//Pressable 컴포넌틀르 사용해서 클릭에 대해 상호작용 할 수 있도록함.
//버튼에 내용표시하기위해 text컴포넌트 사용
const MyButton = props => {
    return (
        <TouchableOpacity
            style={{
                backgroundColor: '#3498db',
                padding: 16,
                margin: 10,
                borderRaduis: 8,
            }}
            onPress={() => alert('click')}
        >
            <Text style={{color: 'white', fotSize: 24}}>
                {props.children || props.title}
                </Text>
        </TouchableOpacity>
    );
};

export default MyButton;



props에 children이 있다면 title보다 우선시 되도록 작성

 

 

defaultProps

App.js에

버튼을 추가하고 아무런 값을 넘겨주지 않으면

<MyButton />

아무 표시가 되지 않는다. 

이러한 일을 방지하기 위해(반드시 전달되어야하는 값이 전달되게 설정)

MyButton.js에

MyButton.defaultProps = {

    title: 'Button',

};

를 추가하면 

MyButton 컴포넌트의 defaultProps 덕분에 기본으로 설정한 Button이 전달되었다.

 

 

 

 

propTypes

컴포넌트에 props를 전달할 때 잘못된 타입을 전달하거나, 필수로 전달해야하는 값을 전달하지 않았을 때

잘못된 props가 전달되었다고 경고하는 방법

컴포넌트에서 전달받아야하는 props의 타입과 필수 여부를 지정할 수 있음

 "npm install prop-types"

MyButton.js

MyButton.propTypes = {
	title: PropTypes.number,
};

title에 전달되어야 하는 값이 number라고 지정함

따라서 이전과 같이 String을 전달할 시 경고 메시지가 나타난다.

 

필수전달여부 => 선언된 타입 뒤에 isRequired만 붙여주면 된다.

MyButton.js

MyButton.propTypes = {
	title: PropTypes.string.isRequired,
    	name: PropTypes.string.isREquired,
};

App.js 에서 name을 전달해주지 않았으므로 에러가 발생하게 된다.

 

함수, 객체, 배열 등의 다양한 타입도 지정할 수 있다.

ex) onPress 필수로 지정

MyButton.js

MyButton.propTypes = {
	title: PropTypes.string.isRequired,
    	onPress: PropTypes.func.isRequired,
};
App.js

...
	    <MyButton title="Button" onPress={()=> alert("Click)}/> 
            <MyButton title="Button onPress={()=> alert("Click)}">
            	Children Props
            </MyButton> 
            <MyButton onPress={()=> alert("Click)}/>
....

 

 

 

 

useState

-State

컴포넌트 내부에서 생성되고 값을 변경할 수 있다.

이를 이용하여 컴포넌트 상태를 관리한다.

state : 컴포넌트에서 변화할 수 있는 값 ( 상태가 변하면 컴포넌트는 리렌더링 된다.)

 

 

useState는 상태를 관리하는 변수, 그 변수를 변경할 수 있는 setter 함수를 배열로 반환한다.

const [state, setState] = useState(initialState);

상태변수 state는 useState 함수에서 반환한 setter함수를 이용하여 변경하여야한다.

호출시 파라미터로 상태의 초기값을 전달한다.

(초기값을 전달하지 않으면 undefined로 설정되어 에러가 발생)

 

./src/component/Counter.js

import React, {useState} from 'react';
import { View, Text } from 'react-native';
import MyButton from './MyButton';

const Counter = () => {
    const [count, setCount] = useState(0);
    return (
        <View style={{ alignItems: 'center'}}>
            <Text style={{fontSize: 30, margin: 10}}>{count}</Text>
            <MyButton title = '+1' onPress={() => setCount(count + 1)} />
            <MyButton title = "-1" onPress={() => setCount(count - 1)} />
        </View>
    )
}

 

import React from 'react';
import {View} from 'react-native';
import Counter from './components/Counter';

const App = () => {
    return (
        <View
            style={{
                flex: 1,
                backgroundColor: '#fff',
                alignItems: 'center',
                justifyContent: 'center',
            }}
        >        

            <counter /> <=counter 컴포넌트 추가

        </View>
    );
};


export default App;

 

728x90
반응형

'공부 > 리액트 네이티브' 카테고리의 다른 글

리액트 네이티브 - 이벤트  (0) 2021.05.06
리액트 네이티브 - props  (0) 2021.05.06
리액트 네이티브 - button 컴포넌트  (0) 2021.05.06
리액트 네이티브 - jsx  (0) 2021.05.06
리액트 네이티브  (0) 2021.05.02
블로그 이미지

아상관없어

,
반응형

컴포넌트 : 재사용 가능한 조립블록, 화면에 나타나는 UI 요소

App.js도 App이라는 컴포넌트이다.

부모로부터 받은 속성이나 자신의 상태에 따라 표현이 달라지고 다양한 기능 수행

 

 

내장 컴포넌트 => App.js의 View나 Text 컴포넌트가 대표적인 내장 컴포넌트

https://reactnative.dev/docs/compnents-and-apis

 

 

Button 컴포넌트

https://reactnative.dev/docs/button

 

./src/App.js

import React from 'react';
import {Text, View, Button} from 'react-native';

const App = () => {
    return (
        <View
        //style 정의
            style={{
                flex: 1,
                backgroundColor: '#fff',
                alignItems: 'center',
                justifyContent: 'center',
            }}
        >
            //출력될 text
            <Text style={{ fontSize: 30, marginBottom: 10 }}>Button Component</Text>
            //버튼에 출력될 text는 title 속성이용, 클릭시 click이 뜨도록 onPress 속성에 함수 지정
            <Button title="Button" onPress={() => alert('Click !!!')} />
        </View>
    );
};

export default App;

 

 

./App.js

import { StatusBar } from 'expo-status-bar';

import App from './src/App'; //./src/App 컴포넌트 사용

export default App;

(button 컴포넌트의 color 속성은 ios에서 텍스트 색을 나타내는 값, 안드로이드에서는 버튼의 바탕색을 나타내는 값)

 

 

 

 

커스텀 컴포넌트

TouchableOpacity 컴포넌트와 Text컴포넌트를 이용해서 MyButton 컴포넌트 생성

(리액트 네이티브 0.63버전에서 Pressable 컴포넌트가 TouchableOpacity컴포넌트를 대체함)

 

 

- ./src에 컴포넌트를 관리할 components 폴더 생성

- MyButton.js 생성

//리액트를 불러와서 사용할 수 있게 해줌(JSX는 React.createElement를 호출 하는 코드로 컴파일 되므로 반드시 작성)
import React from 'react';
//리액트 네이티브에서 제공되는 Pressable, Text 컴포넌트 추가
import{TouchableOpacity, Text} from 'react-native';

//Pressable 컴포넌틀르 사용해서 클릭에 대해 상호작용 할 수 있도록함.
//버튼에 내용표시하기위해 text컴포넌트 사용
const MyButton = () => {
    return (
        <TouchableOpacity>
            <Text style={{fontSize: 24}}>My Button</Text>
        </TouchableOpacity>
    );
};

export default MyButton;

- ./App.js 수정

import React from 'react';
import {Text, View} from 'react-native';
import MyButton from './components/MyButton';

const App = () => {
    return (
        <View
            style={{
                flex: 1,
                backgroundColor: '#fff',
                alignItems: 'center',
                justifyContent: 'center',
            }}
        >        
            <Text
                style={{
                    fontSize: 30,
                    marginBottom: 10,
                }}
            >
                My Button Component
            </Text>
            <MyButton />
        </View>
    );
};

export default App;

 

MyButton이 생성된다.

 

TouchableOpacity컴포넌트는 onPress 속성을 제공하는 TouchableWithoutFeedback 컴포넌트를 상속 받았기 때문에 onPress 속성을 지정하고 사용할 수 있음

//리액트를 불러와서 사용할 수 있게 해줌(JSX는 React.createElement를 호출 하는 코드로 컴파일 되므로 반드시 작성)
import React from 'react';
//리액트 네이티브에서 제공되는 Pressable, Text 컴포넌트 추가
import{TouchableOpacity, Text} from 'react-native';

//Pressable 컴포넌틀르 사용해서 클릭에 대해 상호작용 할 수 있도록함.
//버튼에 내용표시하기위해 text컴포넌트 사용
const MyButton = () => {
    return (
        <TouchableOpacity
            style={{
                backgroundColor: '#3498db',
                padding: 16,
                margin: 10,
                borderRaduis: 8,
            }}
            onPress={() => alert('click')}
        >
            <Text style={{color: 'white', fotSize: 24}}>My Button</Text>
        </TouchableOpacity>
    );
};

export default MyButton;

 

 

728x90
반응형

'공부 > 리액트 네이티브' 카테고리의 다른 글

리액트 네이티브 - props  (0) 2021.05.06
리액트 네이티브 - props  (0) 2021.05.06
리액트 네이티브 - jsx  (0) 2021.05.06
리액트 네이티브  (0) 2021.05.02
자바스크립트 - 정리  (0) 2021.04.30
블로그 이미지

아상관없어

,
반응형

컴포넌트 : 재사용할 수 있는 조립 블럭, 화면에 나타나는 UI요소라고 생각

와이어프레임 : 최종화면에 구성될 콘텐츠를 간단히 요약해서 보여주는 것

 

expo init react-native-component

 

App.js

import { StatusBar } from 'expo-status-bar';
import React from 'react';
import { StyleSheet, Text, View } from 'react-native';

export default function App() {
  return (
    <View style={styles.container}>
      <Text>Open up App.js to start working on your app!</Text>
      <StatusBar style="auto" />
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'center',
  },
});

javascript 이지만 html과 같은 코드들이 보인다. 이러한 코드를 jsx라 한다.

jsx는 객체 생성과 함수 호출을 위한 문법적 편의를 제공하기 위해 만들어진 확장기능이다.

export default function App() {
 return (
   <Text>Open up App.js to start working on your app!</Text>
   <StatusBar style="auto" />
 )
}



위와 같이 App.js를 변경하면 
JSX 식에는 부모 요소가 하나 있어야 합니다.ts(2657)
와 같은 에러가 발생한다.

 

JSX에서는 여러개의 요소를 반환하는 경우에도 반드시 하나의 부모로 나머지 요소를 감싸서 반환해야한다.

import { StatusBar } from 'expo-status-bar';
import React from 'react';
import { StyleSheet, Text, View } from 'react-native';

export default function App() {
 return (
   <View style={styles.container}>
    <Text>Open up App.js to start working on your app!</Text>
    <StatusBar style="auto" />
   </View>
 )
}

view는 UI를 구성하는 가장 기본적인 요소이다.

 

view 컴포넌트말고 여러 개의 컴포넌트를 반환하고 싶은 경우 Fragment 컴포넌트를 사용한다.

import { StatusBar } from 'expo-status-bar';
import React, {Fragment} from 'react';
import {Text} from 'reat-native';

export default function App() {
 return (
   <Fragment>
    <Text>Open up App.js to start working on your app!</Text>
    <StatusBar style="auto" />
   </Fragment>
 )
}

/*
==============
export default function App() {
 return (
   <>
    <Text>Open up App.js to start working on your app!</Text>
    <StatusBar style="auto" />
   </>
 )
}
와 같이 사용하여도 됨
*/

import React, {Fragment} from 'react';

Fragment를 사용하기 위해 import를 이용하여 불러오고 Fragment  컴포넌트를 사용하도록 함

 

 

<name 변수에 이름 넣어서 출력>

import { StatusBar } from 'expo-status-bar';
import React from 'react';
import {StyleSheet, Text, View} from 'react-native';

export default function App() {
 const name = 'Changmin'
 return (
   <View style = {styles.container}>
     <Text style={styles.text}>My name is {name}</Text>
   </View>
 )
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'center',
  },
  text:{
    fontSize: 30,
  },
});

 

 

JSX내부에서 if문을 사용할 수 있지만 즉시실행함수 형태로 작성해야한다.

(즉시 실행 함수)

----------------------------------------------------------------------------

함수를 정의함과 동시에 바로 실행하는 함수

(function (name) { console.log('즉시실행함수' + name); })('foo'); 또는

- function 삭제 가능

( (name) => { console.log('즉시실행함수' + name); })();

----------------------------------------------------------------------------

import { StatusBar } from 'expo-status-bar';
import React from 'react';
import {StyleSheet, Text, View} from 'react-native';

export default function App() {
 const name = 'abcd'
 return (
   <View style = {styles.container}>
     <Text style={styles.text}>
      {(() => {
        if (name === 'Changmin') return 'My name is Changmin';
        else if (name === 'Noname') return 'My name is Noname';
        else return 'My name is react-native';
      })()}
     </Text>
   </View>
 )
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'center',
  },
  text:{
    fontSize: 30,
  },
});

 

jsx에서는 false는 랜더링 되지 않는다.

따라서

name === 'name' && (실행할 코드)

name !== 'name' && (실행할 코드) 

처럼 특정 조건일때 컴포넌트의 랜더링 여부를 결정할 수 있다.

 

 

Inline 스타일링

jsx에서는 style에 문자열로 입력하는 것이 아니라 객체형태로 입력해야한다.

-으로 연결된 이름은 하이픈을 제거하고 카멜표기법으로 작성해야한다. camelCode

import { StatusBar } from 'expo-status-bar';
import React from 'react';
import {Text, View} from 'react-native';

export default function App() {
 return (
   <View
      style = {{
        flex: 1,
        backgroundColor: '#fff',
        alignItems: 'ceonter',
        justifyContent: 'center',
      }}
    >
      <Text>Open up App.js to start working on your app!</Text>
    </View>
 )
}

728x90
반응형
블로그 이미지

아상관없어

,
반응형

오픈소스 프로젝트

사용자 인터페이스를 만드는 리액트에 기반을 두고 제작

ios/Android에서 동작하는 네이티브 모바일 앱을 만드는 자바스크립트 프레임워크

 

장점

- 코드 대부분이 플랫폼(ios/android)간 공유가능

- 패스트 리프레쉬로 변경된 코드를 저장하기만 해도 확인가능

 

단점

- 네이티브의 새로운 기능을 사용하는데 오래 걸림

- 유지보수 어려움

- 잦은 업데이트

 

리액트 네이티브 CLI를 이용하여 리액트 네이티브 프로젝트 생성

npx react-native init 프로젝트이름 --version x.xx.x

 

npx react-native init MyFirstCLI

cd MyFirstCLI

npm run android or npx react-native run-android

 

리액트 네이티브가 실행되면서 Metro가 실행된다.

Metro는 리액트 네이티브가 실행될 때마다 자바스크립트 파일들을 단일 파일로 컴파일 하는 역할을 한다.

 

npm run android 시 gradle 에러가 나는데 jdk16버전에서 jdk14버전으로 바꾸니 해결되었다.

따라서 정상적으로 실행되면 다음과 같다

 

 

 

 

 

MyFirstCLI 폴더에 src 폴더를 생성 후 App.js파일을 생성한다.

./src/App.js

import React from 'react'
import {View, StyleSheet, Text} from 'react-native';
const App = () => {
    return(
        <View style={styles.container}>
            <Text style={styles.title}>My First React Native</Text>
        </View>
    );
};

const styles = StyleSheet.create({
    container: {
        flex: 1,
        justifyContent: 'center',
        alignItems: 'center',
        backfroundColor: '#ffffff',
    },
    title: {
        fontsize: 30,
    },
});

export default App;

 

./App.js 를 다음과 같이 바꾼다.

import App from './src/App';

export default App;

./index.js

import {AppRegistry} from 'react-native';
import App from './src/App';
import {name as appName} from './app.json';

AppRegistry.registerComponent(appName, () => App);

 

첫 화면을 구성하는 파일만 변경하고 리액트 네이티브에서 사용되는 파일을 모두 src 폴더에서 관리하도록 한다.

 

728x90
반응형
블로그 이미지

아상관없어

,
반응형

var / let

var은 

var a = 'a'

var a= 'b'

가 가능하므로 let을 사용

let은 한번 선언하면 재선언불가하고 재할당 가능하다.

 

== / ===

==은 자동으로 타입변환을 하여 값을 비교하지만

===은 타입변환을 하지않고 값을 비교한다. 따라서 값과 타입이 같아야한다.

 

for in / for of

for in은 객체에 사용(객체 프로퍼티 접근) => ex) foo = { name : 'foo' ~~~~}

for of는  iterable한(반복되는) 객체에 사용, 주로 값을 찾을 때 사용(원소에 접근) => foo = [1, 2, 3 ~~]

 

함수 표현식

함수 리터럴로 하나의 함수를 만들고 생성된 함수를 변수에 할당함

//함수 이름 사용
fuction add(x,y){
	return x+y
}
add(3,4)



//익명함수 사용 => 위와같이 함수 이름이 없다
const add = function(x,y){
	return x+y
}

add(3, 4)

 

기본인자

const print = fucntion ( defaultVal = 'default'){
	console.log(defaultVal)
}

 

함수 호이스팅

//호이스팅

add(3, 4) //=>undefined
function add (x, y){
	return x+y
}

add(3, 4) // 에러
const add = function (x, y){
	return x+y
}

console.log(add)//undefined => add 선언 전 undefined로 초기화
add(3, 4)// 에러 add는 함수가 아님
var add = function (x, y){
	return x+y
}

함수를 const 변수에 할당하여 변수처럼 취급

 

Arrow function => 함수 간단히

const nothing = function (x){
	return x
}

console.log(nothing(1))

//fucntion 삭제 가능
const nothing1 = (x) =>{
	return x
}
console.log(nothing1(1))

//괄호 삭제가능 매개변수가 한개일 경우
const nothing2 = x =>{
	return x
}
console.log(nothing2(1))

//중괄호, return 삭제가능 함수 안 표현식이 1개인 경우만
const nothing3 = x => x
console.log(nothing3(1))

 

 

배열관련 메소드

reverse => 배열 원소 반대로 정렬

push => 맨끝에 원소 추가

pop => 맨끝 원소 삭제

unshift => 맨 앞에 원소 추가

shift => 맨 앞 원소 삭제

include(val) => 배열이 val을 가지고 있는지 판단 (참/거짓)

indexOf(val) => val이 존재하면 첫번째로 찾은 val의 인덱스값 반환, 없으면 -1 반환

const num = [1, 1, 3, 1, 3]

num.indexOf(3) => 2반환

join(구분자) => 기본(join())은 "," 

const test = [1, 2, 3]

console.log(test.join("+"))
console.log(test.join("-"))
console.log(test.join(","))
console.log(test.join(" and "))

 

*callback 함수

익명함수의 대표적인 예시

함수를 등록하기만 하고 이벤트가 발생하거나 특정 시점에 도달했을 때 시스템에서 호출되는 함수

or

함수의 인자로 넘겨서 코드 내부에서 호출되는 함수

 

 

forEach

const arr = [1, 2, 3, 4, 5]

arr.forEach((element, index, array) => {
    console.log('elemnet :'+ element)
    console.log('index :'+index)
    console.log(array)
})

===========================================
elemnet :1
index :0
[ 1, 2, 3, 4, 5 ]
=>[ 1, 2, 3, 4, 5 ]배열에서 원소 1의 index는 0

elemnet :2
index :1
[ 1, 2, 3, 4, 5 ]
=>[ 1, 2, 3, 4, 5 ]배열에서 원소 2의 index는 1

elemnet :3
index :2
[ 1, 2, 3, 4, 5 ]
=>[ 1, 2, 3, 4, 5 ]배열에서 원소 3의 index는 2

elemnet :4
index :3
[ 1, 2, 3, 4, 5 ]
=>[ 1, 2, 3, 4, 5 ]배열에서 원소 4의 index는 3

elemnet :5
index :4
[ 1, 2, 3, 4, 5 ]
=>[ 1, 2, 3, 4, 5 ]배열에서 원소 5의 index는 4

 

 

map => 기존 배열을 새 배열로 만들 때 사용(기존 배열이 변하지 않음)

array.map(callbackFunction(element, index, array), thisArg)

thisArg = callback함수 내에서 this로 사용될 값

const arr = [1, 2, 3, 4, 5]

const returnArr = arr.map((element, index, array) => {
		console.log(element)
        console.log(index)
        console.log(array)
        return element*2;
    })
    
 console.log(returnArr)
 
 =========================
1
0
[ 1, 2, 3, 4, 5 ]

2
1
[ 1, 2, 3, 4, 5 ]

3
2
[ 1, 2, 3, 4, 5 ]

4
3
[ 1, 2, 3, 4, 5 ]

5
4
[ 1, 2, 3, 4, 5 ]


[ 2, 4, 6, 8, 10 ]

 

 

filter

콜백 함수의 반환값이 참인 값만 반환 => 필터링

const num = [10, 20, 30, 40, 50]

const result = num.filter((num)=>{
	return num>=30
})

console.log(result)

=> [30, 40, 50]

=>결과가 true를 반환한 원소들로만 배열을 만든다.

find는 요소를 반환

 

reduce => 콜백 함수의 반환값 acc에 누적

reduce(function(acc, currentValue, currentIndex, array){ , initialValue);

acc = 콜백의 반환값 누적

currentValue = 현재 처리할 요소 (옵션)

currentIndex = 현재 처리할 요소 인덱스 (옵션)

array = reduce() 호출할 배열 (옵션)

initialValue = 초기값 (옵션 => 초기값이 없으면 배열의 첫번째 요소 사용)

//콜백 함수 이용시 밑의 function처럼 콜백함수 이름을 적어도 되고 안적어도됨
const result = [0, 1, 2, 3, 4].reduce(function(acc, currentValue, currentIndex, array){
    console.log(`currentIndex : ${currentIndex}`);
    console.log(`currentValue : ${currentValue}`);
    console.log(`currentIndex : ${currentIndex}`);
    console.log(`acc : ${acc}`);
    return acc + currentValue;
}, 0); //acc의 초기값은 0

console.log("result:", result);

==========================
currentIndex : 0
currentValue : 0
currentIndex : 0
acc : 0

currentIndex : 1
currentValue : 1
currentIndex : 1
acc : 0

currentIndex : 2
currentValue : 2
currentIndex : 2
acc : 1

currentIndex : 3
currentValue : 3
currentIndex : 3
acc : 3

currentIndex : 4
currentValue : 4
currentIndex : 4
acc : 6

result: 10

 

find => callback 함수에 정의한 조건에 맞는 배열의 첫번째 요소를 리턴 (없으면 undefined)

find(callback(element, index, array)

const arr = [
  {name: 'a', age : 10}, 
  {name: 'b', age : 20},
  {name: 'c', age: 30}
];

const result = arr.find((arr) => {
	return arr.name == 'a'
})

console.log(result)

=>{ name: 'a', age: 10 }

 

 

some => callback함수에서 true를 리턴하면 true 리턴, 하나라도 참이면 참 반환

array.some(callback(currentValue, index, array), thisArg)

const num = [10,20,25,40,50]

const overThrity = num.some((val) => {
	return val>30
 })
 console.log(overThrity)
 
 
 const underThrity = num.some((val) => {
	return val<30
 })
  console.log(underThrity)
  
   const overFifty = num.some((val) => {
	return val>50
 })
   console.log(overFifty)
   
   
===========
true
true
false

 

 

every => callback함수에서 모든 요소가 참이면 참

const num = [10,20,25,40,50]

const overThrity = num.every((val) => {
	return val>30
 })
 console.log(overThrity)
 
 
 const underThrity = num.every((val) => {
	return val<30
 })
  console.log(underThrity)
  
   const underFifty = num.every((val) => {
	return val<=50
 })
   console.log(underFifty)
   
 ========
false
false
true

 

728x90
반응형
블로그 이미지

아상관없어

,
반응형

- 자바스크립트에서의 배열은 크기를 지정하지 않아도 된다.

- 어떤 위치에 어느 타입의 데이터를 저장하더라도 에러가 발생하지 않는다.

 

 

배열 리터럴

- 자바스크립트에서 새로운 배열을 만드는 데 사용하는 표기법이다.

- [] 대괄호를 사용한다.

var Arr = ['a', 'b', 'c', 'd', 'e'];

 

동적으로 배열원소를 추가할 수 있다.

var Arr = [];

Arr[0] = 100;
Arr[5] = 'a';
Arr[10] = true;

console.log(Arr.length); // 10

값을 순차적으로 넣을 필요 없이 아무 인덱스 위치에 값을 추가할 수 있다.

배열의 크기는 인덱스 중 가장 큰값을 기준으로 정해진다.

(모든 배열은 length 프로퍼티를 가진다.)

 

*length 프로퍼티

length 프로퍼티는 명시적으로 값을 변경할 수 도 있다.

var arr = [0, 1, 2];

console.log(arr.length); // 3

arr.length = 6;
console.log(arr.length); // 6
//[0, 1, 2, undefined, undefined, undefined]

arr.length = 2; // arr[2]인 2값은 삭제된다.
console.log(arr); // 0, 1
console.log(arr[2]); // undefined

push()메소드를 통하여 새로운 원소값을 추가할 수 있다.

(배열의 크기도 늘어난다.)

 

배열과 객체의 차이점

var arr = ['a', 'b', 'c'];

console.log(arr[0]);
console.log(arr[1]);
console.log(arr[2]);
//a, b, c


var obj = {
		'0' : 'a',
        '1' : 'b',
        '2' : 'c'
};
// => 프로퍼티 속성 이름이 '0', '1', '2'이다.

console.log(obj[0]); //=> 자동으로 toString으로 변환되어 obj['0']으로 인식한다.
console.log(obj[1]);
console.log(obj[2]);
//a, b, c


//typeof로 비교 => 둘다 objcet이다.
console.log(typeof arr); // object (not array)
console.log(typeof obj); // object

//length=> 객체는 length 프로퍼티가 없다.
console.log(arr.length); // 3
console.log(obj.length); // undefined

//push => 객체는 배열이 아니므로 표준 배열 메소드를 사용할 수 없다.
// 객체 리터럴 방식으로 생성한 객체는 Object.prototype 객체가 프로토타입이므로
arr.push('d'); //['a', 'b', 'c', 'd']
obj.push('d'); // Uncaught TypeError : Object #<Object> has no method 'push'

 

객체 -> Object.prototype

배열 -> Array

728x90
반응형

'공부 > 리액트 네이티브' 카테고리의 다른 글

리액트 네이티브 - jsx  (0) 2021.05.06
리액트 네이티브  (0) 2021.05.02
자바스크립트 - 정리  (0) 2021.04.30
자바스크립트 - 참조타입(객체) 1  (0) 2021.04.30
자바스크립트 - 기본타입  (0) 2021.04.30
블로그 이미지

아상관없어

,
반응형

자바스크립트에서 기본타입을 제외한 모든 값은 객체이다.

배열, 함수, 정규표현식 등도 모두 객체로 표현된다.

객체는 참조타입이라고 불림 => 객체의 모든 연산이 실제 값이 아닌 참조값으로 처리되기 때문

 

객체 생성

- 자바스크립트는 클래스 개념이 없다.

- 객체 리터럴이나 생성자 함수 등 별도의 생성 방식을 사용함

1. Object() 객체 생성자 함수 이용

//foo 빈 객체 생성
var foo = new Object(); 


//foo 객체 프로퍼티 생성
foo.name = 'foo';
foo.age = 30;
foo.gender = 'male';


console.log(typeof foo);
console.log(foo);

//출력
//object
//{name: 'foo', age: 30, gender: 'male'}

 

2. 객체 리터럴 방식 이용

리터럴 = 표기법

객체리터럴 = 객체 생성하는 표기법

{프로퍼티_이름 : 값}를 이용하여 객체 생성

//객체 리터럴 방식으로 객체 생성
var foo={	
	name : 'foo',	
    	age : '30',	
    	gender : 'male'
    };

 

3. 생성자 함수 

함수를 통하여 객체 생성 가능

 

 

객체 프로퍼티 접근

[] 또는 . 표기법으로 접근

//객체 생성
var foo = {
	name : 'foo',
    	major : 'conputer'
};

//읽기
console.log(foo.name); //  foo
console.log(foo['name']); // foo
console.log(foo.nickname); // undefined


//수정
foo.major = 'electronics';
console.log(foo.major); // electronics
console.log(foo['major']); // electronics


//객체 프로퍼티 동적 생성
foo.age=30;
console.log(foo.age); // 30


//대괄호 표기법만 사용해야하는 경우
foo['full-name'] = 'foo bar'; //동적으로 'full-name' 프로퍼티 생성

console.log(foo['full-name']);// foo bar
console.log(foo.full-name); // NaN

console.log(foo.full); // undefined
console.log(name); // undefined



- [] 사용시 접근하려는 프로퍼티 이름을 문자열 형태로 만들어야함

(자바스크립트에서는 대괄호 표기법에서 접근하려는 프로퍼티 이름을 문자열 형태로 만들지 않으면, 모든 자바스크립트 객체에서 호출가능한 toString() 메소드를 호출하여 문자열로 바꿈)

- 대괄호 표기법만 사용해야하는 경우가 있음 => 접근하려는 프로퍼티가 표현식이거나 예약어일 경우

      full-name의 경우 - 연산자가 있는 표현식임

      console.log(foo.full-name); 와 같이 마침표로 표기할경우 Not a Number이라고 표시된다.

      NaN은 수치연산을 해서 정상적인 값을 얻지 못할때 출력된다. ex) 1 - 'hello' (숫자 - 문자열)

      foo.full-name은 (foo.full) - name으로 취급한다.

 

* for in문

var prop;
for (prop in foo){
	console.log(prop, foo[prop]);
}

 

 

객체 프로퍼티 삭제

var foo = {
	name : 'foo',
    nickname : 'babo'
};


console.log(foo.nickname); // babo

delete foo.nickname; // 삭제

console.log(foo.nickname); // undefined


delete foo; // delete는 프로퍼티만 삭제된다.
console.log(foo.name); // foo

 

 

 

참조 타입 특성

var obj1 = {
	val : 40
};

var obj2 = obj1;


console.log(obj1.val); //40
console.log(obj2.val); //40

obj2.val = 50;

console.log(obj1.val); //50
console.log(obj2.val); //50

obj1은 객체를 저장하는 것이 아니라 객체를 가리키는 참조값을 저장한다.

obj2=obj1을 하면 obj2도 obj1이 가리키는 참조값을 가지게 된다.

따라서 obj1,2가 가리키는 객체는 동일한 객체이다.

 

 

객체비교

var a = 100;
var b = 1--;

var obj1 = {value: 100};
var obj2 = {value: 100);
var obj3 = obj2;

console.log(a == b); // true
console.log(obj1 == obj2); // false 다른 객체를 참조하므로
console.log(obj2 == obj3); // true 같은 객체를 참조하므로

 

 

참조에 의한 함수 호출 (call by reference)

var a =100;
var obj = { value: 100};

function changeArg(num, obj){
	num = 200;
    	obj.value = 200;
        
        console.log(num);
        console.log(obj);
}


changeArg(a, obj);// 200 {value: 200}
=> num에 100 값이 전달되고 200으로 바뀜, ojb.value = 200이 됨

console.log(a); //100
console.log(obj);// {value: 200} 참조에 의한 호출이므로

 

 

프로토타입

- 모든 객체는 자신의 부모 역할을 하는 객체와 연결되어 있음

- 객체지향의 상속과 같이 부모 객체의 프로퍼티를 자신의 것처럼 사용할 수 있음

- 부모객체를 프로토타입 객체라고 함

var foo = {
	name: 'foo',
    	age : 30
};

//foo 객체의 toString 메소드 호출 => foo객체의 프로토타입에 toString이 정의되어 있음
foo.toString();

console.dir(foo);

 

크롬에서 실행하게되면 __proto__ 프로퍼티가 있는 것을 알 수 있다.

 

모든 객체는 자신의 부모 역할을 하는 프로토타입 객체를 가리키는 숨겨진 프로퍼티가 있음.

크롬에서는 __proto__가 숨겨진 프로퍼티이다.

 

모든 객체의 프로토타입은 자바스크립트의 룰에 따라 객체를 생성할 때 결정된다. 

객체 리터럴 방식으로 생성된 객체는 Object.prototype 객체가 프로토타입 객체가 된다.

728x90
반응형

'공부 > 리액트 네이티브' 카테고리의 다른 글

리액트 네이티브 - jsx  (0) 2021.05.06
리액트 네이티브  (0) 2021.05.02
자바스크립트 - 정리  (0) 2021.04.30
자바스크립트 - 참조타입(객체) 2(배열)  (0) 2021.04.30
자바스크립트 - 기본타입  (0) 2021.04.30
블로그 이미지

아상관없어

,
반응형

자바스크립트에서 기본 타입은 숫자, 문자열, boolean, null, undefined라는 타입이 있다.

자바스크립트는 변수를 선언할 때 타입을 미리 정하지 않고, var라는 한가지 키워드로만 변수를 선언한다.

 

//예시

//숫자
var intNUM = 1;

//문자열 타입
var Str = 'asdf';
var Str2 = "Asdfasd";
var Char = 'a';

//boolean
var blool = true;

//undefined
var emptyVar;

//null
var nullVar = null;


//타입은 typeof 연산자를 이용하여 확인한다.
typeof intNUM;
..
...

 

숫자

- 자바스크립트는 하나의 숫자형만 존재

- 자바스크립트는 모든 숫자를 64비트 부동 소수점 형태로 저장하기 때문

- 모든 숫자를 실수로 처리하므로 나눗셈 연산시 주의해야함

EX) 5/2를하면 2.5가 나온다

소수점을 버리고 정수부분만 구하고 싶으면 Math.floor(숫자) 메소드 사용 

 

 

문자열

- 작은따옴표나 큰 따옴표로 생성

- 자바스크립트에서는 char타입과 같이 문자 하나만을 별도로 나타내는 데이터 타입은 존재하지 않음

- 한번 정의된 문자열은 변하지 않는다.(한번 생성된 문자열은 읽기만 가능, 수정은 불가)

var str = 'test';
console.log(str[0]. str[1], str[2], str[3]); //=> test

str[0] = 'T';
console.log(str); //=> test로 소문자가 나온다. 
//한번 정의된 문자열은 변하지 않는다.

- 문자열은 문자 배열처럼 인데그슬 이용하여 접근 가능

 

 

boolean

- true, false값 가짐

 

null, undefined

- 값이 비어있음을 나타냄

- 기본적으로 값이 할당되지 않은 변수는 undefined임

- undefined 타입의 변수는 변수 자체값이 undefined임 => undefined가 타입이면서 값이다.

 

- null의 경우는 명시적으로 값이 비어있음을 나타낸다.

- null의 타입은  object로 ==을 사용하여 변수의 값을 확인해야함

typeof nullVar == null (x)
nullVar == null (o)

 

 

 

 

 

 

728x90
반응형
블로그 이미지

아상관없어

,