본문 바로가기

React Native

앱제작 4 - 메뉴 추가 컴포넌트 작성하기 state

1. useState 는 import 필요

2. useState를 초기화 해준다. 

3. onPress 동작 함수 안에 inputList가 추가될 수 있도록 코드 작성 

 

MenuInputfunc.jsx

import React, {useState} from 'react'; //component 클래스 필요 없다. 
import {
    StyleSheet, Text, View, Image, TextInput, Button, Alert, ScaolView,
    SafeAreaView, //아이폰 기종에 따른 위에 공백때문에
    ScrollView,
    TouchableOpacity,
} from 'react-native';

const MenuInputFunc = () => { //화살표 함수

    const [inputList, setInputList] = useState(["짜장면","돈까스","김치찌개"]); //inputList : 사용할 수 있는 변수 값 setInputList : 첫번쨰 변수를 세팅할 수 있는 함수 


    let inputListComp = inputList.map((menu) => {
        return (
            <TextInput
            style={{
                borderWidth: 1,
                padding: 10,
                width: "80%",
                borderRadius: 5,
                marginBottom: 20
            }}
            value={menu}
            placeholder='메뉴입력' />

        )
    })


    return(
        <View style={{ height: 300, alignItems: 'center' }}>
            {inputListComp}
            <TouchableOpacity
                onPress={() => { //반드시 세팅함수로 구현해야한다. 
                   let newArray=[...inputList, ""]; //누르면 newArray에 저장하기 
                   setInputList(newArray); //newArray를 세팅 함수를 통해 세팅함
                }}
                style={{ width: 100, backgroundColor: 'blue', alignItems: 'center', padding: 10, borderRadius: 10 }}>
                <Text style={{
                    color: 'white',
                    fontWeight: '900',
                    fontSize: 20
                }}>
                    함수형 메뉴 추가</Text>

            </TouchableOpacity>

        </View>

    );
}


export default MenuInputFunc;