컴퓨터뽀개버리기

React Native 튜토리얼(textinput, touch, scroll) 본문

대학생 흔적/ReactNative

React Native 튜토리얼(textinput, touch, scroll)

그순간을기억해 2019. 7. 11. 17:08
반응형
react

Handling Text Input

  • TextInput은 사용자가 텍스트를 입력 할 수 있는 기본 component이다.
  • onChangeText : 텍스트를 변경할 때 마다 호출
  • onSubmitEdition : 텍스트가 제출 될 때 호출
import React, { Component } from 'react';
import { AppRegistry, Text, TextInput, View } from 'react-native';

export default class PizzaTranslator extends Component {
  constructor(props) {
    super(props);
    this.state = {text: ''};
  }

  render() {
    return (
      <View style={{padding: 10}}>
        <TextInput
          style={{height: 40}}
          placeholder="Type here to translate!"
          onChangeText={(text) => this.setState({text})}
        />
        <Text style={{padding: 10, fontSize: 42}}>
          {this.state.text.split(' ').map((word) => word && '🍕').join(' ')}
        </Text>
      </View>
    );
  }
}

// skip this line if using Create React Native App
AppRegistry.registerComponent('AwesomeProject', () => PizzaTranslator);

어떤 텍스트를 입력하든 각 단어를 "🍕"로 번역되는 코드이다.
“Hello there Bob” -> "“🍕🍕🍕” 으로 해석된다.

근데 여기서 코드를 보면 낯선 코드가 있다. 일단 그 부분의 정의를 살펴보면 다음과 같다.

map 함수
파라미터로 전달 된 함수를 통해 배열 내의 각 요소를 프로세싱하여 새로운 배열을 생성한다
() => {}
ES6에 새로 도움된 arrow function 이다.

var materials = [
  'Hydrogen',
  'Helium',
  'Lithium',
  'Beryllium'
];

console.log(materials.map(material => material.length));
// expected output: Array [8, 6, 7, 9]

이렇게 materials의 문자열 길이를 material배열로 생성
한다. 다시 헷갈리는 부분을 살펴보자

{this.state.text.split(' ').map((word) => word && '🍕').join(' ')}

이 코드는 결국 입력된 텍스트를 ’ '로 나눈다음 map을 이용해서 iteration하며 피자를 연결한다.

textinput 깊게 알아보기
https://facebook.github.io/react-native/docs/textinput

Handling Touches

사용자는 버튼을 클릭, 스크롤, 지도를 확대 하는 등의 다양한 제스처 조합을 사용할 수 있다.
React Native는 모든 종류의 공통 제스처를 처리할 수 있는 component와 고급 제스처를 인식하는 포괄적인 Gesture Responder System(https://facebook.github.io/react-native/docs/gesture-responder-system)를 제공한다.
여기서는 일단 가장 기본적인 버튼 터치를 살펴본다.

Displaying a basic button

일단 버튼을 표시하는 가장 간단한 예시이다.

<Button 
	onPress={()  =>  { 
		Alert.alert('You tapped the button!');  			  		   
		}} 
		title="Press Me"  
/>

좀 더 다양한 모양의 버튼을 생성하고 눌렀을 때 alert가 나오는 코드는 다음과 같다.

import React, { Component } from 'react';
import { Alert, AppRegistry, Button, StyleSheet, View } from 'react-native';

export default class ButtonBasics extends Component {
  _onPressButton() {
    Alert.alert('You tapped the button!')
  }

  render() {
    return (
      <View style={styles.container}>
        <View style={styles.buttonContainer}>
          <Button
            onPress={this._onPressButton}
            title="Press Me"
          />
        </View>
        <View style={styles.buttonContainer}>
          <Button
            onPress={this._onPressButton}
            title="Press Me"
            color="#841584"
          />
        </View>
        <View style={styles.alternativeLayoutButtonContainer}>
          <Button
            onPress={this._onPressButton}
            title="This looks great!"
          />
          <Button
            onPress={this._onPressButton}
            title="OK!"
            color="#841584"
          />
        </View>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
   flex: 1,
   justifyContent: 'center',
  },
  buttonContainer: {
    margin: 20
  },
  alternativeLayoutButtonContainer: {
    margin: 20,
    flexDirection: 'row',
    justifyContent: 'space-between'
  }
});

// skip this line if using Create React Native App
AppRegistry.registerComponent('AwesomeProject', () => ButtonBasics);

Touchables

  • 기본 버튼이 앱에 적합하지 않은 경우 React Native가 제공하는 터치가능한 구성 요소 중 하나를 사용하여 버튼을 직접 만들 수 있다.
  • Touchables component는 태핑 제스처를 캡처하는 기능을 제공하며 제스처가 인식되면 피드백을 표시할 수 있다.
  • 예쁘게 보이기 위해선 약간의 작업이 필요하다

피트백의 종류마다 버튼의 이름이 다르다.

  • TouchableHighlight : 사용자가 버튼을 누르면 뷰의 배경이 어둡게 된다
  • TouchableNativeFeedback : android에서만 가능, 터치에 반응하는 잔물결을 표시할 수 있다
  • TouchableOpacity : 사용자가 버튼을 누르는 동안에 버튼의 불투명도가 낮아지면서 배경을 볼 수 있다
  • TouchableWithoutFeedback : 피드백이 없는 기본 버튼
  • onLongPress : 일정 시간 동안 보기를 누르고 있으면 이를 감지한다
import React, { Component } from 'react';
import { Alert, AppRegistry, Platform, StyleSheet, Text, TouchableHighlight, TouchableOpacity, TouchableNativeFeedback, TouchableWithoutFeedback, View } from 'react-native';

export default class Touchables extends Component {
  _onPressButton() {
    Alert.alert('You tapped the button!')
  }

  _onLongPressButton() {
    Alert.alert('You long-pressed the button!')
  }


  render() {
    return (
      <View style={styles.container}>
        <TouchableHighlight onPress={this._onPressButton} underlayColor="white">
          <View style={styles.button}>
            <Text style={styles.buttonText}>TouchableHighlight</Text>
          </View>
        </TouchableHighlight>
        <TouchableOpacity onPress={this._onPressButton}>
          <View style={styles.button}>
            <Text style={styles.buttonText}>TouchableOpacity</Text>
          </View>
        </TouchableOpacity>
        <TouchableNativeFeedback
            onPress={this._onPressButton}
            background={Platform.OS === 'android' ? TouchableNativeFeedback.SelectableBackground() : ''}>
          <View style={styles.button}>
            <Text style={styles.buttonText}>TouchableNativeFeedback</Text>
          </View>
        </TouchableNativeFeedback>
        <TouchableWithoutFeedback
            onPress={this._onPressButton}
            >
          <View style={styles.button}>
            <Text style={styles.buttonText}>TouchableWithoutFeedback</Text>
          </View>
        </TouchableWithoutFeedback>
        <TouchableHighlight onPress={this._onPressButton} onLongPress={this._onLongPressButton} underlayColor="white">
          <View style={styles.button}>
            <Text style={styles.buttonText}>Touchable with Long Press</Text>
          </View>
        </TouchableHighlight>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    paddingTop: 60,
    alignItems: 'center'
  },
  button: {
    marginBottom: 30,
    width: 260,
    alignItems: 'center',
    backgroundColor: '#2196F3'
  },
  buttonText: {
    padding: 20,
    color: 'white'
  }
});

// skip this line if using Create React Native App
AppRegistry.registerComponent('AwesomeProject', () => Touchables);

Using a ScrollView

스크롤이 가능한 항목은 같을 필요 없으며 horizontal 속성을 설정해서 가로 및 세로로 스크롤 할 수 있다.
이 예제는 이미지와 텍스트가 혼합된 수직 스크롤을 생성한다.

import React, { Component } from 'react';
import { AppRegistry, ScrollView, Image, Text } from 'react-native';

export default class IScrolledDownAndWhatHappenedNextShockedMe extends Component {
  render() {
      return (
        <ScrollView>
          <Text style={{fontSize:96}}>Scroll me plz</Text>
          <Image source={{uri: "https://facebook.github.io/react-native/img/favicon.png", width: 64, height: 64}} />
          <Image source={{uri: "https://facebook.github.io/react-native/img/favicon.png", width: 64, height: 64}} />
          <Image source={{uri: "https://facebook.github.io/react-native/img/favicon.png", width: 64, height: 64}} />
          <Image source={{uri: "https://facebook.github.io/react-native/img/favicon.png", width: 64, height: 64}} />
          <Image source={{uri: "https://facebook.github.io/react-native/img/favicon.png", width: 64, height: 64}} />
          <Text style={{fontSize:96}}>If you like</Text>
          <Image source={{uri: "https://facebook.github.io/react-native/img/favicon.png", width: 64, height: 64}} />
          <Image source={{uri: "https://facebook.github.io/react-native/img/favicon.png", width: 64, height: 64}} />
          <Image source={{uri: "https://facebook.github.io/react-native/img/favicon.png", width: 64, height: 64}} />
          <Image source={{uri: "https://facebook.github.io/react-native/img/favicon.png", width: 64, height: 64}} />
          <Image source={{uri: "https://facebook.github.io/react-native/img/favicon.png", width: 64, height: 64}} />
          <Text style={{fontSize:96}}>Scrolling down</Text>
          <Image source={{uri: "https://facebook.github.io/react-native/img/favicon.png", width: 64, height: 64}} />
          <Image source={{uri: "https://facebook.github.io/react-native/img/favicon.png", width: 64, height: 64}} />
          <Image source={{uri: "https://facebook.github.io/react-native/img/favicon.png", width: 64, height: 64}} />
          <Image source={{uri: "https://facebook.github.io/react-native/img/favicon.png", width: 64, height: 64}} />
          <Image source={{uri: "https://facebook.github.io/react-native/img/favicon.png", width: 64, height: 64}} />
          <Text style={{fontSize:96}}>What's the best</Text>
          <Image source={{uri: "https://facebook.github.io/react-native/img/favicon.png", width: 64, height: 64}} />
          <Image source={{uri: "https://facebook.github.io/react-native/img/favicon.png", width: 64, height: 64}} />
          <Image source={{uri: "https://facebook.github.io/react-native/img/favicon.png", width: 64, height: 64}} />
          <Image source={{uri: "https://facebook.github.io/react-native/img/favicon.png", width: 64, height: 64}} />
          <Image source={{uri: "https://facebook.github.io/react-native/img/favicon.png", width: 64, height: 64}} />
          <Text style={{fontSize:96}}>Framework around?</Text>
          <Image source={{uri: "https://facebook.github.io/react-native/img/favicon.png", width: 64, height: 64}} />
          <Image source={{uri: "https://facebook.github.io/react-native/img/favicon.png", width: 64, height: 64}} />
          <Image source={{uri: "https://facebook.github.io/react-native/img/favicon.png", width: 64, height: 64}} />
          <Image source={{uri: "https://facebook.github.io/react-native/img/favicon.png", width: 64, height: 64}} />
          <Image source={{uri: "https://facebook.github.io/react-native/img/favicon.png", width: 64, height: 64}} />
          <Text style={{fontSize:80}}>React Native</Text>
        </ScrollView>
    );
  }
}

// skip these lines if using Create React Native App
AppRegistry.registerComponent(
  'AwesomeProject',
  () => IScrolledDownAndWhatHappenedNextShockedMe);

  • pagingEnabled : 페이징으로 스와이프 제스처 사용
  • ViewPagerAndroid : 안드로이드에서 가로 스와이프
  • ScrollView : iOS에서 확대 축소가능하다. maximumZoomScale, minimumZoomScale props를 설정하면 좀 더 다양한 기능을 사용할 수 있다. 스크롤뷰는 제한된 크기의 작은 양을 표현하는데 적합하다.
  • FlatList : 화면에 표시 할 수 있는 것보다 항목이 긴 경우에 사용한다.
반응형

'대학생 흔적 > ReactNative' 카테고리의 다른 글

React Native Package 설치 및 설정  (0) 2019.07.24
TourAPI 사용법  (0) 2019.07.14
React Native 튜토리얼(style, layout)  (0) 2019.07.11
React Native 시작  (0) 2019.07.11