【问题标题】:How to use React Native basic hooks example? [closed]如何使用 React Native 基本钩子示例? [关闭]
【发布时间】:2021-07-12 03:28:47
【问题描述】:

我最近开始使用 React Native 进行应用开发。因此,我正在尝试实现一个按钮,该按钮通过钩子在两个布尔状态之间切换。现在该按钮可以工作一次,但我无法将值切换回来。我正在尝试创建一个自定义按钮,所以从 React 切换不是一个选项。您对我有任何修复或提示吗?

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

export const Notes =({}) => { 
 //   
    const [score, setScore] = useState(1);

    const handlepress = () => {
        score ? setScore(1): setScore(2);
    }
    return (    
        <View>  
        <Text>{score}</Text>
            <Button title= "Take Number" onPress= {handlepress}>
            </Button>    
            <Text> Test{score}</Text>
        </View>    
);}

【问题讨论】:

  • 如果score 是任何truthy 值,score ? setScore(1): setScore(2); 将调用setScore(1)12 都是真实的,因此代码将始终调用 setScore(1)。如果你想在12 之间来回切换,你需要改变你正在测试的条件。 (另外,我推荐if 语句,而不是独立的条件表达式。)
  • 感谢 T.J. 的快速回复。将来肯定会研究这个并使用 if 语句:)

标签: javascript react-native react-hooks


【解决方案1】:

您想将01 用于score 变量。 12 都是真值,状态永远不会改变。

【讨论】:

    【解决方案2】:

    试试这个方法

    export const Notes =({}) => { 
    
        const [score, setScore] = useState(1); // add score here 
    
        const handlepress = () => {
            score === 2 ? setScore(1): setScore(2);
        }
        return (    
            <View>  
            <Text>{`${score}`}</Text>
                ...    
                <Text>{`Test${score}`}</Text>
            </View>    
    );}
    

    【讨论】:

    • 感谢您的快速回复。我收到错误 ReferenceError: score is not defined。有语法错误吗?
    • @Chris 更新我的答案请检查
    • 非常感谢!那工作得很好。我会深入了解它,你做了什么不同的事情! @nooruddin
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-15
    • 2021-04-02
    • 2020-12-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-10
    相关资源
    最近更新 更多