Flex

旅人·2023년 3월 27일
0

지난 번에 제작한 todo 에서 많은 텍스트를 추가할 경우

추가된 텍스트가 모바일 화면에 다 담기지 않는다.

react native에서 각 요소의 크기 비율을 flex를 통해 지정할 수 있다고 함.

Example(Sandbox.js)

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

export default function Sandbox() {
  return (
    <View style={styles.container}>
      <Text style={styles.boxOne}>one</Text>
      <Text style={styles.boxTwo}>two</Text>
      <Text style={styles.boxThree}>three</Text>
      <Text style={styles.boxFour}>four</Text>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    // flex: 1, // takes all the available space
    flexDirection: "row", // default : 'column'
    justifyContent: "space-around",
    alignItems: "flex-end",
    paddingTop: 40,
    backgroundColor: "#ddd",
  },
  boxOne: {
    flex: 1,
    backgroundColor: "violet",
    padding: 10,
  },
  boxTwo: {
    flex: 2,
    backgroundColor: "gold",
    padding: 20,
  },
  boxThree: {
    flex: 1,
    backgroundColor: "coral",
    padding: 30,
  },
  boxFour: {
    flex: 3,
    backgroundColor: "skyblue",
    padding: 40,
  },
});

flexbox개념이나 justifyContent, alignItems 등은 웹에서의 flexbox와 유사한 개념인듯

만약에 모바일 전체의 배경색을 파란색으로 하고 싶다면

flex:1, backgroundColor:'blue'로 주면 된다.

실행화면


Code

import {
  StyleSheet,
  Text,
  View,
  FlatList,
  Alert,
  TouchableWithoutFeedback,
  Keyboard,
} from "react-native";
import React, { useRef, useState } from "react";
import Header from "./components/header";
import TodoItem from "./components/todoItem";
import AddTodo from "./components/addTodo";


export default function App() {
  const [todos, setTodos] = useState([
    { text: "Javascript", key: "1" },
    { text: "Python", key: "2" },
    { text: "C#", key: "3" },
    { text: "Ruby", key: "4" },
    { text: "Kotlin", key: "5" },
    { text: "Swift", key: "6" },
    { text: "Java", key: "7" },
  ]);

  const size = todos.length;
  const nextId = useRef(size);

  const pressHandler = (key) => {
    setTodos((prevTodos) => prevTodos.filter((todo) => todo.key != key));
  };

  const submitHandler = (text) => {
    if (text.length > 3) {
      nextId.current++;

      setTodos((prevTodos) => [
        ...prevTodos,
        { text: text, key: nextId.current.toString() },
      ]);
    } else {
      Alert.alert("OOPS!", "Todos must be over 3 chars long.", [
        { text: "UnderStood", onPress: () => console.log("alert closed") },
      ]);
    }
  };

  return (
    // <Sandbox />
    <TouchableWithoutFeedback
      onPress={() => {
        Keyboard.dismiss();
      }}
    >
      <View style={styles.container}>
        {/* header */}
        <Header />
        <View style={styles.content}>
          {/* to from */}
          <AddTodo submitHandler={submitHandler} />
          <View style={styles.list}>
            <FlatList
              data={todos}
              renderItem={({ item }) => (
                <TodoItem item={item} pressHandler={pressHandler} />
              )}
            />
          </View>
        </View>
      </View>
    </TouchableWithoutFeedback>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: "#fff",
    // alignItems: "center",
    // justifyContent: "center",
  },
  content: {
    flex: 1,
    padding: 40,
    // backgroundColor: "pink",
  },
  list: {
    flex: 1,
    marginTop: 20,
    // backgroundColor: "yellow",
  },
});

먼저 FlatList를 담고 있는 content 스타일에 flex : 1을 주어서

안의 텍스트가 많아지더라도 화면 밖(밑)으로 튀어나가지 않도록 한다.

그리고 각 텍스트에도 flex : 1 을 주어서

content 내부에서 각자 동일한 크기의 자리를 차지하도록 함.
(안 그러면 밑에 짤리는 요소가 생김)

실행화면

스크롤하여 모든 텍스트를 확인 가능


참고

https://www.youtube.com/watch?v=C4ikFaP0a5o&list=PL4cUxeGkcC9ixPU-QkScoRBVxtPPzVjrQ&index=15

https://yuddomack.tistory.com/entry/5React-Native-%EB%A0%88%EC%9D%B4%EC%95%84%EC%9B%83-%EB%94%94%EC%9E%90%EC%9D%B8-1%EB%B6%80-flex%EC%99%80-width-height

profile
一期一会

0개의 댓글