본문 바로가기

카테고리 없음

ReactNative 리액트 네이티브 사용자 이름을 업데이트

728x90

App.js

import React from 'react';
import { View } from 'react-native';
import { AppProvider } from './AppContext';
import Profile from './Profile';

const App = () => {
  return (
    <AppProvider>
      <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
        <Profile />
      </View>
    </AppProvider>
  );
};

export default App;

Profile.js

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

const Profile = () => {
  const { username, updateUsername } = useContext(AppContext);
  const [newUsername, setNewUsername] = useState('');

  const handleUpdateUsername = () => {
    updateUsername(newUsername);
    setNewUsername('');
  };

  return (
    <View>
      <Text>Username: {username}</Text>
      <TextInput
        style={{ borderWidth: 1, padding: 10, marginVertical: 10 }}
        placeholder="Enter new username"
        value={newUsername}
        onChangeText={setNewUsername}
      />
      <Button title="Update Username" onPress={handleUpdateUsername} />
    </View>
  );
};

export default Profile;

AppContext.js

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

const AppContext = createContext();

const AppProvider = ({ children }) => {
  const [username, setUsername] = useState('');

  const updateUsername = (newUsername) => {
    setUsername(newUsername);
  };

  const contextValue = {
    username,
    updateUsername,
  };

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

export { AppContext, AppProvider };

728x90