简体   繁体   English

如何使用 react-native onPress 更改变量

[英]How to change variable with react-native onPress

I am training in react-native, but I have some comprehension problems.我在 react-native 训练,但我有一些理解问题。

Why can change the "modalVisible" variable, but I cannot change "aux".为什么可以更改“modalVisible”变量,但不能更改“aux”。

const App = () => {  

  const [modalVisible, setModalVisible] = useState(0);    
  var aux = 0;    
  const _onPress  = (code) => {
    aux = 1
    setModalVisible(code)
  };
  return (
    <SafeAreaView style = {styles.centeredView}>
        <View style = {styles.box}>
        <Pressable
            onPress = {() => _onPress(modalVisible+1)} 
            style={styles.pressable}
          > 
            <Text style = {{color:'black'}}>{modalVisible} {aux}</Text>
          </Pressable></View> 
      </View>
    </SafeAreaView>
  );
};

I deleted some views, so it's not ready for a 'crtl + c' 'crtl + v'我删除了一些视图,所以它还没有准备好 'crtl + c' 'crtl + v'

When you change the state of variable using useState hooks, the re rendering of the component take place and the new updated value is shown.当您使用useState挂钩更改变量的 state 时,将重新渲染组件并显示新的更新值。

In case of regular variable, aux in this example, even though the value is changed, the re rendering does not occur and the new updated value is not shown.如果是常规变量,在本例中为aux ,即使值发生更改,也不会发生重新渲染,并且不会显示新的更新值。

There is a similar questions here: useState hooks and regular variable这里有一个类似的问题: useState hooks and regular variable

you need use setState To cause new render你需要使用setState来引起新的渲染

just add只需添加

const [aux, setAux] = useState(0);

then to change it use setAux(1)然后更改它使用setAux(1)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM