【问题标题】:Using useState in React Native在 React Native 中使用 useState
【发布时间】:2021-04-02 01:00:32
【问题描述】:

完全是一个初学者的问题,只是试图在按下按钮时增加一个变量,这是成功的尝试通过创建一个 if 语句来使变量更有趣,其中 count 在达到 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;

【问题讨论】:

  • 当你想改变count时你应该使用setCount。例如,setCount(count &gt; 10 ? 0 : count+1) .

标签: reactjs react-native react-hooks use-state


【解决方案1】:
    const counter = () => {
    if ( count >= 10 )
    {
     setCount(0)
     return
    }
    setCount(count+1)
    }

【讨论】:

    【解决方案2】:

    您可以在 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",
      },
    });
    

    【讨论】:

      猜你喜欢
      • 2021-05-27
      • 2020-07-18
      • 2021-01-17
      • 1970-01-01
      • 2021-09-16
      • 2021-11-15
      • 2021-10-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多