차근차근 생활 & 코딩

[React Native] RN - 토글 스위치(Toggle switch) 구현하기 본문

IT/REACT NATIVE(리액트 네이티브)

[React Native] RN - 토글 스위치(Toggle switch) 구현하기

ssilook 2022. 3. 7. 21:09
반응형

안녕하세요.

 

이번 시간에는 토글 스위치를 만들어 보도록 하겠습니다.

 

Switch 모듈을 import 해주도록 합니다.

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

 

useState 를 통해 컴포넌트값을 변경하도록 합니다.

import React, {useState} from 'react';

const [isEnabled, setIsEnabled] = useState(false);

 

스위치가 동작 할수 있도록 함수를 만들어 보도록 하겠습니다.

const toggleSwitch = () => setIsEnabled(previousState => !previousState);

 

토글 스위치 코드를 붙여 넣어주도록 합니다.

<Switch
	trackColor={{false: '#767577', true: '#81b0ff'}}
	thumbColor={isEnabled ? '#f5dd4b' : '#f4f3f4'}
	ios_backgroundColor="#3e3e3e"
	onValueChange={toggleSwitch}
	value={isEnabled}
/>

 

위에 코드를 보면 어려우시니 이해가 쉽도록 전체 코드를 넣어드릴테니 여러분 코드에 간편하게 복사하여 붙여 테스트를 진행하시면 됩니다.

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

const App = () => {
  const [isEnabled, setIsEnabled] = useState(false);
  const toggleSwitch = () => setIsEnabled(previousState => !previousState);

  return (
    <View style={styles.container}>
      <Switch
        trackColor={{false: '#767577', true: '#81b0ff'}}
        thumbColor={isEnabled ? '#f5dd4b' : '#f4f3f4'}
        ios_backgroundColor="#3e3e3e"
        onValueChange={toggleSwitch}
        value={isEnabled}
      />
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    alignItems: 'center',
    justifyContent: 'center',
  },
});

export default App;

기본 App에 붙여 넣으시면 코드 확인 하실 수 있습니다.

 

코드 실행 결과

토글 버튼 결과

 

반응형
Comments