21.01.19

민주·2021년 1월 19일
0

[flex box]

1. flexDirection

<View style={{flex:1, flexDirection:'column'}}>
    <View style={{flex:1, width:50,height:50,
    backgroundColor:'powderblue'}}></View>
    <View style={{flex:2 width:50,height:50,
    backgroundColor:'skyblue'}}></View>
    <View style={{flex:3 width:50,height:50,
    backgroundColor:'steelblue'}}></View>
</View>
- View안에서 style지정 시 {{}}(중괄호 두개)
- flexDirection : view 안의 속성들에 대한 정렬 방향
- 속성 : row, row-reverse, column, column-reverse
- flex : 화면전체를 기준으로 늘어나는 비율(가로세로 크기가 무의미해짐)
- 크기를 선언해줬을 때는 정한 크기가 무의미 해지기 때문에 flex를 넣으면 안된다.
- 브라우저 창을 기준으로 각 View가 View안에 선언 된 플렉스 비율로 늘어난다.
- 부모가 flex가 잡혀 있어야 자식도 flex비율로 나눠질 수 있다
- 위 코드에서는 1:2:3으로 늘어난다.

2. justifyContent

 <View style={{flex:1, flexDirection:'column',
 justifyContent:'space-between'}}>
- justifyContent : y축을 기준으로 자식 View들을 정렬
- 속성 : 
자식 View들이 뭉쳐 있는 상태에서 배치 : flex-start, flex-end, center
여백을 주면서 배치 : space-between, space-around, space-evenly

3. alignItem

<View style={{
      flex:1, 
      flexDirection:'column',
      justifyContent:'center',
      alignItems:'stretch'
      }}>
- x축을 기준으로 자식View들을 정렬
- 속성 : flex-start, flex-end, center, strech
- stretch : x축으로 늘어나는 속성인데 width가 지정되어 있으면 
늘어나지 않는다.

4. flexWrap

<View style={{flex:1, flexDirection:'row',
flexWrap:'wrap'}}>
- 속성 : 
nowrap : 화면을 벗어나도 놔둔다. 
wrap : 화면 넘어가면 줄바꿈

5. alianSelf

<View style={{flex:1, 
        flexDirection:'column',
        justifyContent:'center',
        alignItems:'flex-start' 
        }}>
  <View style={{alignSelf:'flex-start',width:50,height:50,
  backgroundColor:'red'}}></View>
  <View style={{alignSelf:'flex-end', width:50,height:50,
  backgroundColor:'orange'}}></View>
  <View style={{alignSelf:'stretch', height:150,
  backgroundColor:'yellow'}}></View>
</View>
- alignContent와 비슷하게 동작. 다만 각각의 객체별로 적용된다.
- 속성 : flex-start, flex-end, stretch

6. alignContent

<View style={{flex:1, 
      flexDirection:'row',
      flexWrap:'wrap',
      alignContent : 'center'
    }}>
- flexWrap이 적용된 상태에서 위치 및 공간을 제어
- 속성 : 
자식 View들이 뭉쳐 있는 상태에서 배치 : flex-start, flex-end, center
여백을 주면서 배치 : space-between, space-around,
stretch : y축으로 늘어나는 속성인데 width가 지정되어 있으면 
늘어나지 않는다.

[JSX]

import { StyleSheet } from "react-native";

const AppStyle = StyleSheet.create({
    container:{
        flex:1,
        backgroundColor:'white',
        alignItems:"center",
        justifyContent:'center'
    }
});
export default AppStyle;
- Appstyle.js이다
- export default Appstyle; : 
  외부에서 쓸 수 있도록 public으로 변환해 주는 작업
import React, { Component } from 'react';
import {Text, View } from 'react-native';
import AppStyle from './css/AppStyle';

/*export default function App(){}*/

class App extends Component{

  constructor(props){//생성자
    super(props);//뒤에서 자세히 다룸
    console.log('컴포넌트 생성시 바로 호출');
  }
  render() {
    var name ='이민주';//render는 함수니까 var가능
    const gender = '여자'; //코드블록 영역의 상수
    let age = 28; //코드블록 영역의 변수
    return (
      //View 태그 밖은 일반적인 주석 사용이 가능
      <View style={AppStyle.container}>
        {/*태그 안에서는 조금 다른 주석을 사용*/}
        <Text>{name}/{gender}/{age}</Text>
        <Text>{/*기본적으로 이안에서는 if 문을 사용할 수 없다.*/
          1+1 === 2 ? '참':'거짓' //=== : 타입까지 동일하는지 
        }</Text>
          {
            /*굳이 if문을 써야 한다면 */
            (function(){
              if(age == 10){
                return (<Text></Text>);
              }else if(age == 20){
                return (<Text>스물</Text>);
              }else{
                return (<Text>해당없음</Text>);
              }
            })()
          }
      </View>
    );
  }
}
export default App;
- JSX(Java Script XML): Java script를 확장한 문법이다.
- JSX를 활용하면 HTML rendering시 JS문법을 사용할 수 있게 된다.
- import : 외부 컴포넌트(class) 를 불러오기 위해서 사용 된다.
- 변수 선언은 render()안에 해줘야한다.
- 자바스크립트 코드를 사용하고싶으면 {}를 사용해야하고
{}안에서 함수를 사용하고 싶으면 {()=>{함수}} 식으로 사용해야한다
- (function(){})()의 의미는 함수를 다른 함수들보다 빠르게 실행하겠다.
- return문에 태그를 포함하는경우 ()로 감싸줘야한다.

[props]

//이 선언을 해줘야 정상적인 Component기능을 수행
import React from 'react';
import { Button, View } from "react-native";

//name은 App.js에서 받아옴
const PropBtn = ({name})=>{

    var sendMsg = (name)=>{
        alert(name);
    }
    return(
        <View style={{margin:10}}>
            <Button onPress={()=>{sendMsg(name)}} title={name}/>
        </View>
    );
}
export default PropBtn;//public 처리
- Props는 변경이 감지 될 때 마다 render()가 수행 된다.
- 상위 component에서 전달 받은 값 사용.
- Props는 변경 감지시 render()를 호출한다.
- render를 호출한다는거는 다시그린다는 의미
- 함수형에서는 render()가 생략되어있다.
- Props 는 상위 컴포넌트에서 전달 받은 값을 사용하며 변경 불가능하다.

[state]

import React, { Component } from 'react';
import { Button, View } from "react-native";

class StateBtn extends Component{
    constructor(props){
        super(props);//생략하면 에러난다.
        console.log(props);
        //state에 count라는 속성을 만들어 0을 주었다.->초기화
        this.state = {count:0} 
    }
    //class안에 선언 할 때는 이런식으로..
    updateCount = ()=>{
        this.setState({count:this.state.count+1});
    }
    render(){
        return(//return안에는 View가 무조건 있어야한다
            <View style={{margin:10}}>
                <Button title={'state count :
                '+this.state.count.toString()}
                onPress={()=>{this.updateCount()}}/>
            </View>
        );
    }
}
export default StateBtn;
- 변경이 감지 될 때 render()가 실행된다.
- state라는 객체는 클래스 에서만 사용가능(기본적으로 클래스에 내장되어있다.)
- state는 초기값이 설정된 이후에도 변경이 가능
- state는 값이 변경 된 후 setState()라는 함수를 사용해야 적용된다.
- setState()에서 전달한 값 사용
- setState()를 이용해 변경 가능
- 버튼을 누를 때 UI가 변경되는 경우는 state를 활용 해야 한다.
import React, {useState} from 'react';
import { Button, View } from "react-native";

const UseStateBtn = ()=>{

    //함수에서 state를 활용하는 방법
    const[count,setCount] = useState(0);

    var updateCount =()=>{
    	//count에 1을 더해 setCount()를 활용하여 등록
        setCount(count+1);
    }

    return(
        <View style={{margin:10}}>
            <Button title={'useState count : '+count} 
            onPress={()=>{updateCount()}}/>
        </View>
    );
}
export default UseStateBtn;
- state는 class에서만 사용가능하지만 함수에서 state를 활용하는 방법이다.
- class에서 활용할때보다 간결해진다.

[input box]

import React, {useState} from 'react';
import {Text, Button, TextInput, View } from 'react-native';
import AppStyle from '../css/AppStyle';

const InputSample = ()=>{

    /*state에 저장하기*/
    const[text,setText] = useState('');

    var resetProc = ()=>{
        setText('');
    }

    return(
        <View style={AppStyle.container}>
          {/*TextInput에 입력받은 내용을 status에 저장*/}
          <TextInput style={AppStyle.input}
          placeholder="아무거나 입력하세요"
          onChangeText={(text)=>{setText(text)}} 
          value={text}/>
          <View>
             <Button title="초기화" onPress={()=>{resetProc()}}/>
          </View>
            <Text>: {text} </Text>
        </View>
    );
}
export default InputSample;
- 기본적으로 UI의 목적은 서버로 특정 내용을 보내거나 받기 위한 것이다.
- 즉 UI에 있어서 input은 아주 기본적인 기능이다.
- Input에서 입력받은 값을 변경 할 때도 state가 사용된다.
- const [저장 변수, 갱신 함수] = useState(상태 초기 값);
import React, {useState} from 'react';
import {Text, Button, TextInput, View } from 'react-native';
import App from '../App';
import AppStyle from '../css/AppStyle';

//여러개의 input에서 값을 받는 경우..
export default function Inputs(){

    const [inputs,setInputs] = useState({name:'',nick:''});
    console.log(inputs);
    //비구조화 할당(inputs에 있는 내용을 각각 name과 nick에 담는다)
    const {name,nick} = inputs;
    
    const onChange = (key,val)=>{
    /*받아온 key, val을 inputs에 설정
    obj={key:val}
    obj.key = val
    obj[key] =val
    */
    //react에서는 객체의 원본을 함부로 수정하면 안된다.
    //setInputs({[key]:val});
    //그래서 특정 객체 수정시 기존 객체를 복사하고 나서 수정해야한다.
    //그래서 spread를 사용하여 객체 복사(...inputs)
    setInputs({
        ...inputs,
        [key]:val
    });
    }
    return(
        <View style={AppStyle.container}>
           <TextInput style={AppStyle.input} placeholder="아이디"
           onChangeText={(name)=>{onChange('name',name)}} 
           value={name}/>
           <TextInput style={AppStyle.input} placeholder="닉네임"
           onChangeText={(nick)=>{onChange('nick',nick)}} 
           value={nick}/>
           <View>
               <Button title="초기화" 
               onPress={()=>{setInputs({name:'',nick:''})}}/>
            </View>
            <Text>아이디:{name} / 닉네임:{nick}</Text>
        </View>
    )
}
- 여러개의 input을 받는 경우이다.
- key는 그냥 써주면 문자열로 인식해서 [key]:val로 해줘야 변수로 인식한다.
profile
개발이좋아요

0개의 댓글