FE/React & RN

[ React-Native ] 시작

Chars4785 2019. 10. 21. 12:13

@ 궁금한 이유 

한번 DOCS https://facebook.github.io/react-native/docs/getting-started 를 한번 천천히 보면서 공부하고 싶다는 생각에 시작하게 되었다. 제대로 해보고 싶어서


@ 공부

시작하기 위해서 

- Expo

- Android

사용

 

<div>

<span>

or

<Text>

<View> 와 비슷하다고 생각하면 된다.

## moder JavaScript

In the old days, you could just include a <script> tag in the header of your webpage, and your JavaScript would run as intended. These days, we preprocess our JavaScript in order to access experimental features and language extensions like JSX

> 전에 사용한 JS는 나중에 돌아 가도록 했다면 이제는 전처리를 위한 작업을 위해서 JS가 돌아 간다.

## babel

Babel is the main tool used to preprocess JavaScript. Babel is a highly configurable compiler that lets you use experimental features and extensions, compiling down into older versions of JavaScript that can be supported on a wider range of platforms. Of course, if a native platform doesn't support an ES6 feature like Promise(), Babel won't fully be able to help -- but it can in many cases polyfill missing APIs to provide this functionality.

>  버전에 안맞는 문법 같은 경우는 babel 이 도와준다.

 

## ES2015

For the most part, all ES2015 features are now available in modern JavaScript engines. Using Babel, however, gives us access to newer features which aren't yet, while ensuring our JavaScript runs on even more platforms. React Native uses Babel to enable ES2015 (and newer) features and ensure cross-platform consistency, so your JavaScript can run on Android, iOS, Windows, and other platforms

> Babel 덕분에 어느 곳에 든지 JS 를 구동할 수 있게 되었다.

## JSX

 JSX에서 변수를 사용하기 위해서 {} (braces) 를 사용해서 사용한다.

## flex

<View style={{flex: 1,flexDirection: 'row'}}>
      <View style={{width: 50, height: 50, backgroundColor: 'powderblue'}} />
      <View style={{width: 50, height: 50, backgroundColor: 'skyblue'}} />
      <View style={{width: 50, height: 50, backgroundColor: 'steelblue'}} />
</View>

 

flex will define how your items are going to “fill” over the available space along your main axis. Space will be divided according to each element's flex property.

In the following example the red, yellow and the green views are all children in the container view that has flex: 1 set. The red view uses flex: 1 , the yellow view uses flex: 2 and the green view uses flex: 3 . 1+2+3 = 6 which means that the red view will get 1/6 of the space, the yellow 2/6 of the space and the green 3/6 of the space.

 

flex :1 이라고 적으면 전체 비율 만큼 안에서 차지 한다.

## flexDirection

> controls the direction in which the children of a node are laid out.

> 자식 노드의 방향을 정할 수 있다.

 

< View style={{flex: 1, flexDirection: 'row' }} >

1. row

2. column ( default )

3. row-reverse

4. column-reverse

 

 

## TextInput

export default function App() {
  const[state,setState] = useState({
    t:''
  });
  const onChange = (a) =>{
    console.log(typeof(a));
    setState(
      {
        t:a
      }
    );
  }

    return (
      <View style={{padding: 30}}>
        <TextInput
          name="id"
          style={{height: 40}}
          placeholder="Type here to translate!"
          onChangeText={onChange}
        />
        <Text>{state.t}</Text>
      </View>
    );
}

 

## Handing Touches

Button 으로 되어있는 component 가 있다 하지만 button은 이미 이미지를 갖고 있어서 나만의 커스텀한 버튼을 만들기 위해서


# 이미지 없는 button ( react-native import )

TouchableHighlight > 누르게 되면 html button active 가 발동 되는 것 처럼 검은색으로 변함

TouchableNativeFeedback : ( Android only ) > 흐릿하게 뒤에 버튼 누른 것이 그림이 조금씩 생긴다.

TouchableOpacity : 배경은 변하지 않고 글씨 색만 투명해 짐

TouchableWithoutFeedback : 정말 아무것도 원하지 않는다면 

 

 

## View

ScrollView

ScrollView 스크롤을 사용할때 사용합니다. 하지만 horizontally 수평으로 하려면 ViewPager 를 사용해야 합니다.

 

ListView 

- FlatList : two props 를 원한다. data, renderItem 

> data는 리스트 안에 들어갈 데이터

> renderItem 은 각각의 데이터가 어떤 형태로 보였으면 하는 것이다.

( map 으로 보여줘도 되지 않나,, 싶다. )

<FlatList
          data={[
            {key: 'Devin'},
            {key: 'Dan'},
            {key: 'Dominic'},
            {key: 'Jackson'},
            {key: 'James'},
            {key: 'Joel'},
            {key: 'John'},
            {key: 'Jillian'},
            {key: 'Jimmy'},
            {key: 'Julie'},
          ]}
          
          renderItem={({item}) => <Text style={styles.item}>{item.key}</Text>}/>

 

- SectionList :

 <SectionList
          sections={[
            {title: 'D', data: ['Devin', 'Dan', 'Dominic']},
            {title: 'J', data: ['Jackson', 'James', 'Jillian', 'Jimmy', 'Joel', 'John', 'Julie']},
          ]}
          renderItem={({item}) => <Text style={styles.item}>{item}</Text>}
          renderSectionHeader={({section}) => <Text style={styles.sectionHeader}>{section.title}</Text>}
          keyExtractor={(item, index) => index}
        />

 

## NetWorking

fetch

XMLHttpRequest

webSocket

axois

 

# http 통신 과 socket 통신

 

> Client가 요청을 보내는 경우에만 Server가 응답하는 단방향적 통신

 

> 필요한 경우에만 Server로 접근하는 콘텐츠 위주의 데이터를 사용할 때 용이합니다. 만약 게시물에 대한 내용을 요청하기 위해 실시간으로 연결을 유지하는 Socket통신을 사용하게 되면, 게시물을 받은 후에도 계속 통신을 위한 연결이 성립되어 있어 부하가 걸리게 됩니다.

 

> Socket통신은 Http 통신과 달리 Server와 Client가 특정 Port를 통해 연결을 성립하고 있어 실시간으로 양방향 통신을 하는 방식입니다. Client만 필요한 경우에 요청을 보내는 Http 통신과 달리 Socket 통신은 Server 역시 Client로 요청을 보낼 수 있으며, 계속 연결을 유지하는 연결지향형 통신이기 때문에 실시간 통신이 필요한 경우에 자주 사용됩니다. 

 

[ Http 통신의특징 ]

  • Client가 요청을 보내는 경우에만 Server가 응답하는 단방향 통신이다.

  • Server로부터 응답을 받은 후에는 연결이 바로 종료된다. 

  • 실시간 연결이 아니고, 필요한 경우에만 Server로 요청을 보내는 상황에 유용하다.

  • 요청을 보내 Server의 응답을 기다리는 어플리케이션(Android or Ios)의 개발에 주로 사용된다

[ Socket 통신의 특징 ]

  • Server와 Client가 계속 연결을 유지하는 양방향 통신이다.

  • Server와 Client가 실시간으로 데이터를 주고받는 상황이 필요한 경우에 사용된다.

  • 실시간 동영상 Streaming이나 온라인 게임 등과 같은 경우에 자주 사용된다.

 

# axios VS fetch

 

 Axios와 달리 fetch() 는 최신 브라우저에 내장되어 있습니다. 가져오기를 사용하면 타사 패키지를 설치할 필요가 없습니다. 그래서 당신에게 달렸습니다. fetch() 와 함께 할 수도 있고, 당신이 무엇을하는지 알지 못하거나, Axios를 사용하는 것이 더 간단 할 수도 있습니다.

 

> fetch() 는 업데이트가 되는 것이고, axios 는 업데이트를 기다리는 경우도 많다. 하지만 fetch() 가 지원되지 않는 브라우저가 있다. 

> https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch

> fetch에 전반 적인 사용 가이드

 

1. basic

const response = await fetch('http://example.com/movies.json');
const myJson = await response.json();
console.log(JSON.stringify(myJson));

JSON.stringify() 메서드는 JavaScript 값이나 객체를 JSON 문자열로 변환합니다.

console.log(JSON.stringify({ x: 5, y: 6 }));
// expected output: "{"x":5,"y":6}"

console.log(JSON.stringify([new Number(3), new String('false'), new Boolean(false)]));
// expected output: "[3,"false",false]"

console.log(JSON.stringify({ x: [10, undefined, function(){}, Symbol('')] }));
// expected output: "{"x":[10,null,null,null]}"

console.log(JSON.stringify(new Date(2006, 0, 2, 15, 4, 5)));
// expected output: ""2006-01-02T15:04:05.000Z""
import axios from 'axios';
const ApiDefault = {
    url: "/lol",
    key: "XXXXXXXXXXXXXX"
}
ApiDefault.instance = axios.create({
    baseURL: ApiDefault.url
});
getLOLData = async function () {
    if (this.state.input.length <= 0) {
        alert("ID를 입력해주세요") return;
    }
    try {
        const summoner = await ApiDefault.instance.get(`/summoner/v3/summoners/by-name/${this.state.input}?api_key=${ApiDefault.key}`);
        const match = await ApiDefault.instance.get(`/match/v3/matchlists/by-account/${summoner.data.accountId}?api_key=${ApiDefault.key}`);
        const league = await ApiDefault.instance.get(`/league/v3/positions/by-summoner/${summoner.data.id}?api_key=${ApiDefault.key}`);
        this.setState({
            summoner: summoner.data,
            match: match.data,
            league: league.data[0]
        })
    } catch (error) {
        console.error('Data 없음', error);
    }
}

인스턴스를 만들어서 사용하기 편하게 만들었다.