본문 바로가기
Dev/RN

8. [RN] 목록 만들어보기

by VIPeveloper 2021. 1. 30.
반응형

이번 포스팅에서는 목록을 만들어보려고 합니다. props 개념에 대해 조금씩 이해가 되기 시작했습니다.

 

App.js 조작하기

for문을 출력하기 위해서 먼저 state 값에 배열을 넣어줍니다.

그리고 NumList라는 태그를 만들어서 조각으로 데이터를 쏴줍니다.

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

import React,{Component} from 'react';
import { View,Text, StyleSheet } from 'react-native';
import Header from './src/header';
import Generator from './src/generator';
import NumList from './src/numlist';  	--- 1. 추가

class App extends Component{

  state = {
    appName: 'My first app',
    
    --- for문을 출력하기 위해서 먼저 state 값에 배열을 넣어줍니다.
    random: [1,2,3,4,5]				  	--- 2. 추가
  }

  onAddRandomNum = () => {
    alert('add random number');
  }

  render(){
    return (
      <View style={styles.mainView}>
        <Header name={this.state.appName}/>

        <View>
          <Text 
            style={styles.mainText}
            onPress={()=>alert('text touch event')}
            >hello world</Text>
        </View>

        <Generator add={this.onAddRandomNum}/>
        
        --- NumList라는 태그를 만들어서 조각으로 데이터를 쏴줍니다.
        <NumList num={this.state.random}/> 		--- 3. 추가
      </View>
    )
  }
}

const styles = StyleSheet.create({
  mainView: {
    flex: 1,
    paddingTop: 50,
    alignItems: 'center',
    //justifyContent: 'center'
  },
  subView: {
    backgroundColor: 'yellow',
    marginBottom: 10
  },
  anotherView: {
    flex: 2,
    backgroundColor: 'yellow',
    marginBottom: 10 ,
    width: '100%',
    alignItems: 'center',
    justifyContent: 'center'
  },
  mainText:{
    fontSize: 20,
    fontWeight: 'normal',
    color: 'red',
    padding: 20
  }
})

export default App;

 

NumList.js 조작하기

props로 가져온 배열을 나열하기 위해서는 map이라는 것을 이용한다고 합니다. es6문법이라는데. for문 출력해주는 것이라고 알고 있으면 될 것 같네요.

item, idx로 받아서 뿌려주는 역할을 담당합니다.

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

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

const NumList = (props) => {
    return(
        props.num.map((item,idx) =>(
            <View style={styles.numList} key={idx}>
                <Text>{item}</Text>
            </View>
        ))
    )
}

const styles = StyleSheet.create({
  numList: {
      backgroundColor: '#cecece',
      alignItems: 'center',
      padding: 5,
      marginTop: 5,
      width:'100%',
      borderRadius: 50
  }
})

export default NumList;

리스트 출력이 잘 되었습니다.

 

끝.

반응형