Artır ve azalt
- React Native kursu
- Başlangıç
- Ders 21/116
- 6 dk
Artırma ve azaltma butonlarını eklersin.
Artır ve azalt fonksiyonları
Sayacı değiştirmek için iki fonksiyon tanımlayacağız: increment sayıyı bir artırır, decrement bir azaltır. Bu fonksiyonlar setCount'u çağırır.
Örnek: function increment() { setCount(count + 1); }. Burada count + 1 yeni değer olarak setCount'a verilir.
Fonksiyonları App bileşeni içinde, return'den önce tanımlarız. Böylece count ve setCount'a erişebilirler.
Fonksiyon tanımı
Bir fonksiyonu bileşen içinde tanımlamak, onun count ve setCount'a erişmesini sağlar. Bu, React'in closure davranışından gelir.
Tanımlar: function increment() { setCount(count + 1); } ve function decrement() { setCount(count - 1); }.
Bu fonksiyonları şu an çağırmıyoruz; bir sonraki derste butonlara bağlayacağız. Şimdilik sadece tanımları ekliyoruz.
Uygulama Fonksiyonları ekle
Mevcut App bileşenine increment ve decrement fonksiyonlarını ekle. increment setCount(count + 1), decrement setCount(count - 1) çağrısı yapsın. Fonksiyonları return'den önce tanımla.
Başlangıç kodu
import { View, Text } from 'react-native';
import { useState } from 'react';
export default function App() {
const [count, setCount] = useState(0);
return (
<View>
<Text>Sayaç: {count}</Text>
</View>
);
}Örnek çözüm
import { View, Text } from 'react-native';
import { useState } from 'react';
export default function App() {
const [count, setCount] = useState(0);
function increment() {
setCount(count + 1);
}
function decrement() {
setCount(count - 1);
}
return (
<View>
<Text>Sayaç: {count}</Text>
</View>
);
}Soru ve cevaplar
Dersin sorularını cevaplarıyla birlikte inceleyebilirsin. Kendini denemek istersen dersi interaktif olarak çöz.
1 Fonksiyonları eşleştir
| Kavram | Anlamı |
|---|---|
increment |
Bir artırır |
decrement |
Bir azaltır |
setCount |
Atayıcı |
count + 1 |
Artış miktarı |
2 increment gövdesi
function increment() {
____;
}
function increment() {
setCount(count + 1);
}
Açıklama: setCount(count + 1) sayıyı bir artırır.
3 decrement fonksiyonu ne yapmalı?
- setCount(count + 1)
- decrement(count)
- count - 1
- setCount(count - 1) Doğru cevap
Açıklama: decrement sayıyı bir azaltır.