在 React Native 中使用 useState

Using useState in React Native

完全是一个新手问题,只是试图在按下按钮时增加一个变量,这是成功的尝试通过制作一个 if 语句使计数在达到 10 时设置回零但似乎没有变得更有趣工作

App.js

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

const HelloWorldApp = () => {

  const [count, setCount] = useState(0);

  const counter = () => {
    if ( count > 10 )
    {
      count == 0;
    }
    setCount(count+1)
  }

  return (
    <View style={{
        flex: 1,
        justifyContent: 'center',
        alignItems: 'center'
      }}>
      <Text style={styles.baseText} >Hello, world! x{count}</Text>
      <Button onPress={counter} title="Click me!"/>
    </View>
  );
}
const styles = StyleSheet.create({
  baseText: {
    fontFamily: "Cochin",
    fontSize: 20,
    fontWeight: "bold"
  },
});


export default HelloWorldApp;
    const counter = () => {
    if ( count >= 10 )
    {
     setCount(0)
     return
    }
    setCount(count+1)
    }

您可以在 setCount 中检查条件..

import React, { useState } from "react";
import { Text, View, Button, StyleSheet } from "react-native";

const HelloWorldApp = () => {
  const [count, setCount] = useState(0);

  const counter = () => {
    setCount((prev) => (prev >= 10 ? 0 : prev + 1));
  };

  return (
    <View
      style={{
        flex: 1,
        justifyContent: "center",
        alignItems: "center",
      }}
    >
      <Text style={styles.baseText}>Hello, world! x{count}</Text>
      <Button onPress={counter} title="Click me!" />
    </View>
  );
};
const styles = StyleSheet.create({
  baseText: {
    fontFamily: "Cochin",
    fontSize: 20,
    fontWeight: "bold",
  },
});