NativeBase


NativeBase는 React Native용 UI 컴포넌트 라이브러리이다. 



1
npm install native-base --save

cs

해당 명령어로 라이브러리를 설치한다.



1
react-native link

cs

link 명령어로 라이브러리와 프로젝트를 연결한다. 


설치가 잘되면 다음과같은 메세지가 나온다.




1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
import React, { Component } from 'react';
import { Container, Header, Title, Content, Footer, FooterTab, Button, Left, Right, Body, Icon, Text } from 'native-base';
export default class AnatomyExample extends Component {
  render() {
    return (
      <Container>
        <Header>
          <Left>
            <Button transparent>
              <Icon name='menu' />
            </Button>
          </Left>
          <Body>
            <Title>Header</Title>
          </Body>
          <Right />
        </Header>
        <Content>
          <Text>
            This is Content Section
          </Text>
        </Content>
        <Footer>
          <FooterTab>
            <Button full>
              <Text>Footer</Text>
            </Button>
          </FooterTab>
        </Footer>
      </Container>
    );
  }
}
cs

[NativeBase1.js]


doc사이트에 있는 간단한 예제를 실행해 보자 .


1
2
3
import NativeBase1 from './NativeBase1';
 
export default NativeBase1;
cs

[App.js]


App.js를 주석처리하고 위와 같이 코드를 변경하고 프로젝트를 실행한다.


NativeBase 컴포넌트를 이용하여 헤더, 컨텐트, 푸터를 간단하게 생성할 수 있다.


원문참조 : NativeBase


블로그 이미지

클라인STR

,

fetch API

fetch API는 Ajax를 비동기형태로 쉽게 사용할 수 있는 api 함수이다. 

1
2
3
4
5
6
7
8
9
10
11
12
fetch('http://example.com/movies.json')
  .then(function(response) {
    return response.json();
  })
  .then(function(myJson) {
    console.log(JSON.stringify(myJson));
})
.catch(function(err) {
console.log(err);
});


cs

URL을 인자로 받고 응답을 처리하기위한 Promise인 response 객체가 반환된다. 


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
import React, {Component} from 'react';
import {Platform, StyleSheet, Text, View, ActivityIndicator} from 'react-native';
 
export default class App extends Component {
 
  constructor(props) {
    super(props);
    this.state = {
      isLoading: true,
      dataSource: null
    }
  }
 
  componentDidMount() {
    return fetch('https://facebook.github.io/react-native/movies.json')
            .then ( (response) => response.json() )
            .then( (responseJson) => {
                this.setState({
                    isLoading: false,
                    dataSource: responseJson.movies,
                })
            })
        .catch((error) => {
            console.log(error)
        });
  }
 
  render() {
      if (this.state.isLoading) {
        return (
            <View style={styles.container}>
                <ActivityIndicator />
            </View>
        )
    } else {
        let movies = this.state.dataSource.map((val, key) => {
            return <View key={key} style={styles.item}><Text>{val.title}</Text></View>
        });
        return (
            <View style={styles.container}>
                
                {movies}
            </View>
        );
    }
  }
}
 
const styles = StyleSheet.create({
  container: {
      flex: 1,
      backgroundColor: '#fff',
      alignItems: 'center',
      justifyContent: 'center',
  },
  item: {
      flex: 1,
      alignSelf: 'stretch',
      margin: 10,
      alignItems: 'center',
      justifyContent: 'center',
      borderBottomWidth: 1,
      borderBottomColor: '#eee'
  }
});
 
cs

[App.js]



map 함수 참고



원문 출처 : https://www.youtube.com/watch?v=hzLDsxPGctY

fetch api : https://blog.naver.com/dmswjd93/221273203218

https://medium.com/@kkak10/javascript-fetch-api-e26bfeaad9b6




블로그 이미지

클라인STR

,

1. 아래 명령어로 react-natvie-vector-icons을 설치한다.


npm install react-native-vector-icons --save



2. link 명령어로 라이브러리와 프로젝트를 연결한다. 


react-native link react-native-vector-icons





3. import 구문을 아래와 같이 추가한다.


import Icon from 'react-native-vector-icons/Ionicons';


https://ionicons.com/  접속하여, Icon 탭에서 사용할 수 있는 아이콘 종류를 확인 할 수 있다. 



아이콘을 클릭하면 다음과 같이 하단부에 확장영역이 뜨며, Style 종류에 따른  svg파일을 다운로드 받을 수 있으면 Web Component Code를 표시한다. 


실제로 RN에서사용할때 플랫폼 접두어(ios 또는 md) + "-"+ name 명을 써서 표시한다. 


메뉴 아이콘을 클릭에서 선택하면 위와 같이 Web Component Code가 표시되는데 RN에서 사용할경우 아래과 같이 코드를 불러서 사용한다. 


<Icon name="ios-menu"  size={30} color="white"/>



아래코드에서 Ionicons 아이콘을 사용한 디자인을 살펴보자 



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
 
import React, {Component} from 'react';
import {Platform, StyleSheet, Text, View, Image, TouchableOpacity} from 'react-native';
import Icon from 'react-native-vector-icons/Ionicons';
 
 
export default class App extends Component {
  render() {
    return (
      <View style={styles.container}>
        <View style={styles.header}>
          <View style={{paddingLeft:10, flex:2}}>
            <Icon name="ios-menu"  size={30} color="white"/>
          </View>
          <View style={{flex:2,justifyContent:'flex-end', flexDirection: 'row'}}>
           <Icon name="ios-notifications-outline" size={30} color="white" />
           <Icon name="ios-search" size={30} color="white" style={{paddingRight:20, paddingLeft:20}} />
          </View>
        </View>
        
      </View>
      
    );
  }
}
 
const styles = StyleSheet.create({
  container: {
    flex: 1
  },header: {
        backgroundColor: '#808080',
        alignItems: 'center',
        justifyContent:'flex-start',
        height:60,
        flexDirection: 'row',
        paddingTop: 20,
    }
});
 
cs

[App.js]






좀더 자세한 내용은 react-native-vector-icons   참조하자


블로그 이미지

클라인STR

,


React-Native-Navigation V2 을 이용하여 SlideMenu 작성해보자. v1에서는 drawer였는데, 버전이 올라가면서 sideMenu로 변경되었다.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
import {Navigation} from 'react-native-navigation';
import Welcome from './src/Welcome';
import SignIn from './src/SignIn';
import SignUp from './src/SignUp';
import SideMenu from './src/SideMenu';

 
 
Navigation.registerComponent('SideMenu', ()=>SideMenu );
Navigation.registerComponent('Welcome', ()=>Welcome );
Navigation.registerComponent('SignIn', ()=>SignIn );
Navigation.registerComponent('SignUp', ()=>SignUp );
 
Navigation.events().registerAppLaunchedListener( () => {
   
  Navigation.setRoot({
    root: {
      sideMenu: {
        left: {
          component: {
            id: "Drawer",
            name"SideMenu",
            passProps: {
              text'This is a left side menu screen'
            },
            
          }
        },
        center: {
          stack : {
            id:'AppStack',
            children : [
                {
                    component : {
                        name'Welcome'
                    },
                }
            ]
          }
        }
      }
    }
  });
 
  
});
 
 
 
cs

[index.js]

Navigation.setRoot root 속성 안으로 sideMenu :{... } 추가한다. 이때 center : {stack: {} ... } 속석을 반드시 지정한다. sideMenu를 설정하면 터치를 오른쪽으로해서 화면을 밀면 자동으로 sideMenu가 오픈된다. 


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
import React, {Component} from "react";
import {
    View,
    Text,
    StyleSheet,
    Button
} from "react-native";
import {Navigation} from "react-native-navigation";
 
class SideMenu extends Component {   
 
    render() {
 
        return (
            <View style={styles.container}>
                <Text>SideMenu</Text>
            </View>
        );
    }
}
 
 
export default SideMenu;
 
 
const styles = StyleSheet.create({
    
    container : {
        flex : 1,
        alignItems: 'center',
        justifyContent : 'center'
    }
});

cs

[SideMenu.js]


SideMenu 컴포넌트는 간단하게 작성한다.



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
import React, { Component } from "react";
import { View, Text, StyleSheet, Button } from "react-native";
import { Navigation } from "react-native-navigation";
 
 
class WelcomScreen extends Component {
 
 
    static get options() {
        return {
            topBar: {
                visibletrue,
                translucent: true,
                background: {
                    color: "rgba(217, 73, 114, 0.5)",
                    
                },
                leftButtons: {
                    id: 'menuButton',
                    icon: require('../image/icons-menu-25.png')
                }                    
                
            }
        };
    }
 
    constructor(props) {
        super(props);
        this.state = {
            openFlag : false
        }
        Navigation.events().bindComponent(this);
        
    }
      
 
 
    navigationButtonPressed({ buttonId }) {
        
        this.state.openFlag = !this.state.openFlag;
        if (buttonId == 'menuButton') {
            Navigation.mergeOptions('Drawer', {
              sideMenu: {
                left: {
                  visible:this.state.openFlag , 
                },
              },
            });
            
        }
        
    }
 
 
    goToScreen = (screenName) => {
        Navigation.push(this.props.componentId, {
            component: {
                name: screenName
            }
        })
    }
 
    render() {
 
        return (
            <View style={styles.container}>
                <Button title='Sign In' onPress={() => this.goToScreen('SignIn')} />
                <Button title='Sign Up' onPress={() => this.goToScreen('SignUp')} />
            </View>
        );
    }
}
 
export default WelcomScreen;
 
const styles = StyleSheet.create({
 
    container: {
        flex: 1,
        alignItems: 'center',
        justifyContent: 'center'
    }
});

cs

[Welcome.js]


static get options 함수를 이용하여 topBar에 관한 설정을 추가하고, leftButton 항목에 버튼이미지및 id를 설정한다. leftButton에 대한 이벤트를 사용하기위해서 생성자함수에 Navigation.events().bindComponent(this); 추가하고

navigationButtonPressed({ buttonId }) {..} 이벤트 발생에 대한 코드를 추가한다.

leftButton선택시 sideMenu를 open 시키기위해서 sideMenu 상태를 재정의 해야된다. 이때 사용되는 메서드가 Navigation.mergeOptions 이다.






참고 URL

https://wix.github.io/react-native-navigation/#/docs/layout-types?id=sidemenu

https://wix.github.io/react-native-navigation/#/docs/topBar-buttons


관련 포스팅 보기 


react-native-navigation v2 개발환경 설정 (ios) #1


react-native-navigation v2 Root Screen #2

react-native-navigation V2 StackNavigator #3 





블로그 이미지

클라인STR

,

React Native Navigation Patterns

블로그 이미지

클라인STR

,
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
 
import {Navigation} from 'react-native-navigation';
import Welcome from './src/Welcome';
import SignIn from './src/SignIn';
import SignUp from './src/SignUp';
 
 
 
Navigation.registerComponent('Welcome', ()=>Welcome );
Navigation.registerComponent('SignIn', ()=>SignIn );
Navigation.registerComponent('SignUp', ()=>SignUp );
 
Navigation.events().registerAppLaunchedListener(()=>{
    Navigation.setRoot({
        root: {
            stack : {
                id:'AppStack',
                children : [
                    {
                        component : {
                            name'Welcome',
                            options:{
                                topBar : {
                                    title:
                                    {
                                        text'Welcome'
                                    }     
                                }
                                
                            }
                        },
                    }
                ]
            }
        }
    })
});
cs

[index.js]


index.js 파일을 root: 부분에 statck 항목을 추가한다. 

Navigation.setRoot() 함수는 탭 또는 스택 또는 이 두 가지의 조합과 같은 모든 종류의 레이아웃에 대한 속성을 받는다.

stack 은 RNN (react-native-navigation) 에서 레이아웃의 한종류이다. 

자식 레이아웃을 지원한다. stack은 둘 이상의 화면으로 초기화 될수 있고 마지막 화면이 스택 맨위에 표시된다.


const stack = {

  children: [

    {

      component: {}

    },

    {

      component: {}

    }

  ],

  options: {}

}




Welcome.js 파일을 아래와 같이 수정한다.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
import React, {Component} from "react";
import {
    View,
    Text,
    StyleSheet,
    Button
} from "react-native";
import {Navigation} from "react-native-navigation";
 
 
class WelcomScreen extends Component {
 
    goToScreen = (screenName) => {
        Navigation.push(this.props.componentId,{
            component : {
                name: screenName
            }
        })
    }
 
    render() {
 
        return (
            <View style={styles.container}>
                <Button title='Sign In' onPress={()=> this.goToScreen('SignIn')} />
                <Button title='Sign Up' onPress={()=> this.goToScreen('SignUp')} />
            </View>
        );
    }
}
 
 
export default WelcomScreen;
 
 
const styles = StyleSheet.create({
    
    container : {
        flex : 1,
        alignItems: 'center',
        justifyContent : 'center'
    }
});
cs

[Welcome.js]



push(componentId, layout)



Navigation Stack에서 새로운 화면을 추가할때 사용하는 메서드이다.



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
import React, {Component} from "react";
import {
    View,
    Text,
    StyleSheet,
    Button
} from "react-native";
import {Navigation} from "react-native-navigation";
 
class SignIn extends Component {   
 
    render() {
 
        return (
            <View style={styles.container}>
                <Text>SignIn</Text>
            </View>
        );
    }
}
 
 
export default SignIn;
 
 
const styles = StyleSheet.create({
    
    container : {
        flex : 1,
        alignItems: 'center',
        justifyContent : 'center'
    }
});


cs

[SignIn.js]



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
import React, {Component} from "react";
import {
    View,
    Text,
    StyleSheet,
    Button
} from "react-native";
 
 
class SignUp extends Component {
    render() {
 
        return (
            <View style={styles.container}>
                <Text>SignUp</Text>
            </View>
        );
    }
}
 
 
export default SignUp;
 
 
const styles = StyleSheet.create({
    
    container : {
        flex : 1,
        alignItems: 'center',
        justifyContent : 'center'
    }
});
cs

[SignUp.js]

블로그 이미지

클라인STR

,

componentDidAppearcomponentDidDisappear 는 component가 나타나고 사라질때 호출되는  React Native Navigation LifeCycle 콜백메서드이다.  (Navigation.events().bindComponent(this) 사용되어진 뒤에 )


React의 componentDidMount, componentWillUnmount 마찬가지로 다른 점은 사용자가 실제로 마운트되어 있는지 여부뿐만 아니라 문제의 구성 요소를 실제로 볼 수 있는지 여부를 나타낸다. React Native Navigation 성능을 최적화하는 방식 때문에, 컴포넌트는 실제로 레이아웃의 일부분으로 탑재되지만, 항상 보이지는 않는다.(예를 들어 다른 화면이 그위에 푸쉬된경우 )


이들을 사용하려면 다른 React LifeCycle 함수와 같이 구성요소에 구현하기 만하면 모든 기능을 자동으로 호출하는 탐색 이벤트 모듈에 화면을 바인딩 한다.


 ScreenLifeCycle 예제 


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
import React, {Component} from "react";
import {
    View,
    Text,
    StyleSheet,
    Button
} from "react-native";
import {Navigation} from "react-native-navigation";
 
class SignIn extends Component {
 
    constructor(props) {
        super(props);
        Navigation.events().bindComponent(this);
        this.state = {
          text'nothing yet'
        };
      }
 
      componentDidAppear() {
        alert('componentDidAppear');        
      }
    
      componentDidDisappear() {
       alert('componentDidDisappear');
      }
 
    render() {
 
        return (
            <View style={styles.container}>
                <Text>SignIn</Text>
            </View>
        );
    }
}
 
 
export default SignIn;
 
 
const styles = StyleSheet.create({
    
    container : {
        flex : 1,
        alignItems: 'center',
        justifyContent : 'center'
    }
});

cs

[SignIn.js]


[실행화면]


참고 : https://wix.github.io/react-native-navigation/#/docs/Usage?id=screen-lifecycle

블로그 이미지

클라인STR

,



react-native-navigation 줄여서 RNN을 이용하여 UI를 화면에 표시해보자 

먼저 리액트네이티브 react-native-navigation 개발환경 설정 을 통해서 프로젝트를 생성하고 RNN을 사용하기 위한 설정이 필요하다 .



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
// /** @format */
 
// import {AppRegistry} from 'react-native';
// import App from './App';
// import {name as appName} from './app.json';
 
// AppRegistry.registerComponent(appName, () => App);
 
 
import {Navigation} from 'react-native-navigation';
 
import Welcome from './Welcome';
 
Navigation.registerComponent('Welcome', ()=>Welcome );
 
Navigation.events().registerAppLaunchedListener(()=>{
    Navigation.setRoot({
        root: {
            component: {
                name'Welcome'
            }
        }
    })
});

cs


[index.js]


index.js 에서 프로젝트 생성시 자동으로 생성되는 1~7번째 라인 구문을 주석처리한다. 10번째 줄에 react-native-navigation에있는  Navigation 객체를 import 하였다.  12번째 줄에 Welcome.js 파일을 import 하였다.

14번째 라인에 Navigation 객체에 registerComponet메서드를 이용하여 페이지를 등록하였고, 16번째 라인에 Navigation.events().registerAppLaunchedListenerI() 메서드를 이용하여 root 화면을 등록하였다.



Navigation.events().registerAppLaunchedListener(() => {


});

앱이 실행되면 onAppLaunched 이벤트가 실행된다. 이 이벤트는  애플리케이션 레이아웃이 초기화될때 사용된다. 



registerComponent(screenID, generator)


앱에서 사용할화면 구성요소를 등록하며, screenID는 고유한 이름으로 등록되어야 한다. (중복되면안됨) generator 에 경우는 React.Component 또는 React.PureComponent를 확장하는 일반적인 React구성요소가 올 수 있다. 




registerAppLaunchedListener(callback)

앱이 실행되면 registerAppLaunchedListener 이벤트가 호출된다. 

Navigation객체의 setRoot 명령을 통해서 원하는 레이아웃으로 앱을 초기화 할 수 있다. root에 컴포넌트 이름으로 해당React 요소를 로딩한다. 



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
import React, {Component} from "react";
import {
    View,
    Text,
    StyleSheet
} from "react-native";
 
 
class WelcomScreen extends Component {
    render() {
 
        return (
            <View style={styles.container}>
                <Text>WelcomeScreen</Text>
            </View>
        );
    }
}

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

export default WelcomScreen;

cs

[Welcome.js]

React.Component 상속하여 Welcome 화면을 만들었다.


react-native run-ios 명령어를 이용하여 실행해본다.


참고 : https://wix.github.io/react-native-navigation/#/docs/Usage?id=the-basics

블로그 이미지

클라인STR

,