[React Native] ScrollView, TextInput

2020. 12. 24. 12:50React/React Native

1. ScrollView

react-native 모듈로부터 ScrollView를 가져와서 <ScrollView> 태그를 사용하면 된다. ScrollView도 마찬가지로 공식 문서(reactnative.dev/docs/scrollview)에서 다양한 속성들을 확인할 수 있다.

공식 문서

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

...

        <ScrollView 
          style={{width: '100%'}}
          // onMomentumScrollBegin={()=>alert('begin')} // 스크롤링이 끝나면 반응
          // onMomentumScrollEnd={()=>alert('end')} // 스크롤링이 멈추면 반응
          // onScroll={()=>alert('scrolling')} // 스크롤이 움직이면 반응
          // onContentSizeChange={(width, height)=>alert(height)} // 높이값 출력
          bounces={true}
        >

          <NumList 
            num={this.state.random}
            delete={this.onNumDelete}
          />

        </ScrollView>
        
...

 

 

 

2. TextInput

1) 사용 방법

텍스트를 입력하는 컴포넌트이다.

  • src 폴더 하위에 index.js 파일 생성
  • App.js 파일에 import

 

...

import Input from './src/input';

class App extends Component {

  ...

  render() {
    return (
      <View style={styles.mainView}>

        <Input/>

      </View>
    )
  }
}

...
/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 *
 * @format
 * @flow
 */

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

class Input extends Component {

    state = {
        myTextInput: ''
    }

    onChangeInput = (event) => {
        this.setState({
            myTextInput: event
        })
    }

    render() {
        return (
            <View style={styles.mainView}>
                <TextInput
                    style={styles.input}
                    value={this.state.myTextInput} // 입력값을 받아오는 속성
                    onChangeText={this.onChangeInput}

                    multiline={true} // 개행
                    maxLength={100} // 글자 수 제한
                    autoCapitalize={'none'} // 대문자 자동 수정
                    editable={true} // 입력 제한
                />
            </View>
        )
    }
}

const styles = StyleSheet.create({
    mainView: {
        width: '100%',
    },

    input: {
        width: '100%',
        backgroundColor: '#CECECE',
        marginTop: 20,
        fontSize: 25,
        padding: 10
    }
})

export default Input;

TextInput

2) Button, ScrollView, TextInput 혼합

여기서 주의해야할 점은, React Native에서는 부모에서 자식으로 데이터 전달은 가능하지만 반대로 자식에서 부모에게 데이터 전달은 할 수 없다. 따라서 이전에 생성한 Input.js의 코드를 App.js 파일로 옮겨주어야 한다.

import React, { Component } from 'react';
import { View, Text, StyleSheet, ScrollView, Button, TextInput } from 'react-native';

class App extends Component {

  state = {
    myTextInput: '',
    alphabet: ['a','b','c','d']
  }

  onChangeInput = (event) => {
      this.setState({
          myTextInput: event
      })
  }

  // myTextInput에 저장된 입력값을 추가
  onAddTextInput = () => {
    this.setState(prevState => {
      return {
        myTextInput: '',
        alphabet: [...prevState.alphabet, prevState.myTextInput]
      }
    })
  }

  render() {
    return (
      <View style={styles.mainView}>
        <TextInput
                    style={styles.input}
                    value={this.state.myTextInput} // 입력값을 받아오는 속성
                    onChangeText={this.onChangeInput}

                    multiline={true} // 개행
                    maxLength={100} // 글자 수 제한
                    autoCapitalize={'none'} // 대문자 자동 수정
                    editable={true} // 입력 제한
        />
        <Button
          title="Add Text Input"
          onPress={this.onAddTextInput}
        />

        <ScrollView style={{width: '100%'}}>
          {
            this.state.alphabet.map((item, idx) => (
              <Text
                style={styles.mainText}
                key={idx}
              >
                {item}
              </Text>
            ))
          }
        </ScrollView>
      </View>
    )
  }
}

const styles = StyleSheet.create({
  mainView: {
    flex: 1,
    backgroundColor: 'white', 
    paddingTop: 50, 
    alignItems: 'center',
    // justifyContent: 'center'
  },

  subView: {
    backgroundColor: 'yellow',
    marginBottom: 10
  },

  anotherSubView: {
    backgroundColor: 'yellow',
    marginBottom: 10,
    alignItems: 'center',
    justifyContent: 'center'
  },
  
  mainText: {
    fontSize: 20,
    fontWeight: 'normal',
    color: 'red',
    padding: 20,
    margin: 20,
    backgroundColor: 'pink'
  },

  input: {
    width: '100%',
    backgroundColor: '#CECECE',
    marginTop: 20,
    fontSize: 25,
    padding: 10
  }
})

export default App;

Button, ScrollView, TextInput 혼합

728x90