CodeBlanks Logo Icon CodeBlanks

Theme toggle

Tema değiştirme butonu öğrenirsin.

Theme toggle

Tema değişimi (toggle), açık ile koyu arasında geçiş yapar. Bir butona basılınca theme değeri değişir; Provider yeni değeri yayar ve tüm bileşenler güncellenir.

Geçiş, setTheme(theme === light ? dark : light) gibi bir ifadeyle yapılır. Buton onPress'inde bu çağrıyı yaparsın; kullanıcı tek dokunuşla tema değiştirir.

Toggle uygulaması

Toggle için theme ve setTheme'e ihtiyacın var. Bunları useContext(ThemeContext) ile alabilir; ya da toggle işlevini Provider değerine ekleyip yayabilirsin.

Örnek: const toggle = () => setTheme(theme === light ? dark : light). Bu işlevi bir Button'un onPress'ine verirsin. Butona basınca tema anında değişir.

Uygulama Toggle butonu ekle

theme ve setTheme zaten useContext(ThemeContext) ile alındı. Bir toggle butonu ekle: const toggle = () => setTheme(theme === light ? dark : light) ve <Button title="Değiştir" onPress={toggle} />. light ve dark tanımlı.

Başlangıç kodu

App.js
import React, { useContext } from 'react';
import { Button, Text, View } from 'react-native';

const light = { background: '#fff', text: '#000' };
const dark = { background: '#000', text: '#fff' };

const ThemeContext = React.createContext();

export default function App() {
  const { theme, setTheme } = useContext(ThemeContext);
  // toggle butonu ekle
  return (
    <View style={{ backgroundColor: theme.background }}>
      <Text style={{ color: theme.text }}>Tema</Text>
    </View>
  );
}

Örnek çözüm

App.js
import React, { useContext } from 'react';
import { Button, Text, View } from 'react-native';

const light = { background: '#fff', text: '#000' };
const dark = { background: '#000', text: '#fff' };

const ThemeContext = React.createContext();

export default function App() {
  const { theme, setTheme } = useContext(ThemeContext);
  const toggle = () => setTheme(theme === light ? dark : light);
  return (
    <View style={{ backgroundColor: theme.background }}>
      <Text style={{ color: theme.text }}>Tema</Text>
      <Button title="Değiştir" onPress={toggle} />
    </View>
  );
}

Soru ve cevaplar

Dersin sorularını cevaplarıyla birlikte inceleyebilirsin. Kendini denemek istersen dersi interaktif olarak çöz.

1 toggle kavramlarını eşleştir

Kavram Anlamı
toggle Tema değişimi
setTheme Temayı günceller
light Açık tema
dark Koyu tema

2 Toggle butonu ne yapar?

  • Listeyi kaydırır
  • Navigasyon açar
  • Renk üretir
  • Açık ve koyu arasında geçiş yapar Doğru cevap

Açıklama: Toggle, açık ve koyu tema arasında geçiş yapar.

3 Toggle ifadesi

Soru
const toggle = () => setTheme(theme === light ? ____ : light);
Cevap
const toggle = () => setTheme(theme === light ? dark : light);

Açıklama: theme === light ise dark'a geç.

Orta seviye bölümündeki tüm dersler