[ReactNative] Component

HyunDong Lee·2021년 2월 27일
0

reactNative

목록 보기
1/2
post-thumbnail
import { StatusBar } from 'expo-status-bar';
import React, { Fragment } from 'react';
import { StyleSheet, Text, View } from 'react-native';

export default function App() {
  const name = 'Hyun Dong';
  return (
    <View style={styles.container}>
      <Text style={styles.text}>
        {(() => {
          if (name == 'Hyun Dong') return 'My name is HyunDong';
          else if (name == 'Byunjun') return 'My name is Byunjun';
        })()}
      </Text>
      <StatusBar style="auto" />
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'center',
  },
  text: {
    fontSize: 30,
  },
});

3항 연산자

import { StatusBar } from 'expo-status-bar';
import React, { Fragment } from 'react';
import { StyleSheet, Text, View } from 'react-native';

export default function App() {
  const name = 'HyunDong';
  return (
    <View style={styles.container}>
      <Text style={styles.text}>
        My name is {name === 'HyunDong' ? 'ByungJun' : 'ReactNative'}
      </Text>
      <StatusBar style="auto" />
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'center',
  },
  text: {
    fontSize: 30,
  },
});

And, Or 연산자

import { StatusBar } from 'expo-status-bar';
import React, { Fragment } from 'react';
import { StyleSheet, Text, View } from 'react-native';

export default function App() {
  const name = 'HyunDong';
  return (
    <View style={styles.container}>
      {name === 'HyunDong' && (
        <Text style={styles.text}> My name is HyunDong </Text>
      )}
      {name !== 'HyunDong' && (
        <Text style={styles.text}> My name is not HyunDong </Text>
      )}
      <StatusBar style="auto" />
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'center',
  },
  text: {
    fontSize: 30,
  },
});
  • jsx에서 false는 랜더링되지 않기 때문에 AND 연산자 앞의 조건이 참일 때 뒤의 내용이 나타나고, 거짓인 경우 나타나지 않는다.
  • jsx의 경우 null은 허용하지만 undefined는 오류가 발생한다는 데 주의해야 한다.
  • jsx의 주석은 {/**/} 을 사용한다.

스타일링

  • 인라인 스타일링에 대해 살펴보면 jsx에서는 HTML과 달리 STYLE에 문자열로 입력하는것이 아니라 객체 형태로 입력해야 한다.
  • 카멜 표기법 사용

컴포넌트

  • 재사용이 가능한 조립 블록으로 화면에 나타나는 UI요소입니다.
  • 3장에서는 button 컴포넌트의 문서를 확인하면서 title과 onPress 속성을 지정해본다.

Core Components and APIs · React Native

// ./src/App.jsx
import React from 'react';
import { Text, View, Button } from 'react-native';

const App = () => {
  return (
    <View
      style={{
        flex: 1,
        backgroundColor: '#fff',
        alignItems: 'center',
        justifyContent: 'center',
      }}
    >
      <Text style={{ fontSize: 30, marginBottom: 10 }}>Button Component</Text>
      <Button title="Button" onPress={() => alert('Click !!!')} />
    </View>
  );
};

export default App;
// ./src/components/Mybutton.jsx
const MyButton = () => {
  return (
    <TouchableOpacity
      style={{
        backgroundColor: '#3498db',
        padding: 16,
        margin: 10,
        borderRadius: 8,
      }}
      onPress={() => alert('Click !@#')}
    >
      <Text style={{ color: 'white', fontSize: 24 }}>My Button </Text>
    </TouchableOpacity>
  );
};

propTypes

  • 프로젝트의 크기가 커지면서 컴포넌트에 props를 전달할 때 잘못된 타입을 전달하거나, 필수로 전달해야 하는 값을 전달하지 않아서
  • propsTypes에는 문자열이나 숫자 외에도 함수, 객체, 배열 등의 다양한 타입을 지정할 수 있습니다.
//App.jsx
import App from './src/App';

export default App;
///src/App.jsx
import React from 'react';
import { Text, View } from 'react-native';
import MyButton from './components/MyButton';

const App = () => {
  return (
    <View
      style={{
        flex: 1,
        backgroundColor: '#fff',
        alignItems: 'center',
        justifyContent: 'center',
      }}
    >
      <Text style={{ fontSize: 30, marginBottom: 10 }}>Props</Text>
      <MyButton title="Button" onPress={() => alert('props')} />
      <MyButton title="Button" onPress={() => alert('children')}>
        Children Props
      </MyButton>
      <MyButton onPress={() => alert('default!')} />
    </View>
  );
};

export default App;
//src/components/Mybutton.jsx
import React from 'react';
import { TouchableOpacity, Text } from 'react-native';
import PropTypes from 'prop-types';

const MyButton = (props) => {
  //console.log(props);
  return (
    <TouchableOpacity
      style={{
        backgroundColor: '#3498db',
        padding: 16,
        margin: 10,
        borderRadius: 8,
      }}
      onPress={() => props.onPress()}
    >
      <Text style={{ color: 'white', fontSize: 24 }}>
        {props.children || props.title}
      </Text>
    </TouchableOpacity>
  );
};

MyButton.propTypes = {
  title: PropTypes.string.isRequired,
  onPress: PropTypes.func.isRequired,
};

export default MyButton;

State

  • props는 부모 컴포넌트에서 받은 값으로 변경할 수 없는 반면, state는 컴포넌트 내부에서 생성 되고 값을 변경할 수 있으며 이를 이용해 컴포넌트 상태를 관리합니다. 상태란 컴포넌트에서 변화할 수 있는 값을 나타내며, 상태가 변하면 컴포넌트는 리렌더링됩니다.

  • useState 사용하기

    • 리액트 hooks 중 useState는 함수형 컴포넌트에서 상태를 관리할 수 있도록 해줍니다.

      const [state, setState] = useState(initialState);

  • useState는 상태를 관리하는 변수와 그 변수를 변경할 수 있는 세터함수를 배열로 반환합니다.

  • 상태변수는 직접 변경하는 것이 아니라 useState함수에서 반환한 세터 함수를 이용해야합니다.

setter 함수

  • return type은 void 혹은 값의 설정 결괄르 알려줄 수 있는 type이어야 함.
  • argument는 수정할 멤버변수와 같은 type이어야한다.
  • 이름 앞에 set을 붙이고 뒤에는 수정할 멤버변수의 이름 혹은 해당 변수를 직관적으로 표현하는 단어이어야 함.
// ./src/components/Counter.jsx
import React, { useState } from 'react';
import { View, Text } from 'react-native';
import MyButton from './MyButton';

const Counter = () => {
  const [count, setCount] = useState(0);
  return (
    <View style={{ alignItems: 'center' }}>
      <Text style={{ fontSize: 30, margin: 10 }}>{count}</Text>
      <MyButton title="+1" onPress={() => setCount(count + 1)} />
      <MyButton title="-1" onPress={() => setCount(count - 1)} />
    </View>
  );
};

export default Counter;

이벤트(p.94)

  • press 이벤트

    • 웹 프로그래밍에서 가장 많이 사용하는 이벤트 중 하나는 사용자가 특정 DOM을 클릭했을 때 호출되는 onClick 이벤트일 것입니다. 리액트 네이티브에서 onClick 이벤트와 가장 비슷한 이벤트는 press 이벤트이다.
      - onPressIn
      - 터치가 시작될 때
      - onPressOut
      - 터치가 해제 될 때
      - onPress
      - 터치가 해제될 때 onPressOut 이후 호출
      - onLongPress
      - 터치가 일정 시간 이상 지속되면

      //EventButton.jsx
      import React from 'react';
      import { TouchableOpacity, Text } from 'react-native';
      
      const EventButton = () => {
        const _onPressIn = () => console.log('Press In !!!\n');
        const _onPressOut = () => console.log('Press Out !!!\n');
        const _onPress = () => console.log('Press !!!\n');
        const _onLongPress = () => console.log('Long Press!!!\n');
        return (
          <TouchableOpacity
            syle={{
              backgroundColor: '#f1c40f',
              padding: 16,
              margin: 10,
              borderRadius: 8,
            }}
            onPressIn={_onPressIn}
            onLongPress={_onLongPress}
            onPressOut={_onPressOut}
            onPress={_onPress}
          >
            <Text style={{ color: 'white', fontSize: 24 }}>Press</Text>
          </TouchableOpacity>
        );
      };
      export default EventButton;

0개의 댓글