【发布时间】: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 > 10 ? 0 : count+1).
标签: reactjs react-native react-hooks use-state