본문 바로가기

카테고리 없음

ReactNatine 리액트네이티브 버튼 클릭 수 증가 코드

728x90

App,js

import React from 'react';
import { View, Text } from 'react-native';
import { AppProvider } from './AppContext';
import Counter from './Counter'; // Counter 컴포넌트 import

const App = () => {
  return (
    <AppProvider>
      <Counter />
    </AppProvider>
  );
};

export default App;

 

AppContext.js

import React, { createContext, useState } from 'react';

const AppContext = createContext();

const AppProvider = ({ children }) => {
  const [count, setCount] = useState(0);

  const increment = () => {
    setCount(prevCount => prevCount + 1);
  };

  const contextValue = {
    count,
    increment,
  };

  return (
    <AppContext.Provider value={contextValue}>
      {children}
    </AppContext.Provider>
  );
};

export { AppContext, AppProvider };
 

 

Counter.js

import React, { useContext } from 'react';
import { View, Text, TouchableOpacity } from 'react-native';
import { AppContext } from './AppContext';

const Counter = () => {
  const { count, increment } = useContext(AppContext);

  const handleIncrement = () => {
    increment();
  };

  return (
    <View>
      <Text>Count: {count}</Text>
      <TouchableOpacity onPress={handleIncrement}>
        <View style={{ backgroundColor: 'blue', padding: 10, marginTop: 10 }}>
          <Text style={{ color: 'white', fontSize: 16 }}>Increment</Text>
        </View>
      </TouchableOpacity>
    </View>
  );
};

export default Counter;

728x90