【问题标题】:How to change variable with react-native onPress如何使用 react-native onPress 更改变量
【发布时间】:2021-06-01 14:52:12
【问题描述】:

我正在接受 react-native 培训,但我有一些理解问题。

为什么可以更改“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>
  );
};

我删除了一些视图,所以它还没有准备好 'crtl + c' 'crtl + v'

【问题讨论】:

    标签: javascript react-native


    【解决方案1】:

    当您使用useState 钩子更改变量的状态时,会重新渲染组件并显示新的更新值。

    如果是常规变量,本例中为aux,即使值发生变化,也不会发生重新渲染,也不会显示新的更新值。

    这里有类似的问题:useState hooks and regular variable

    【讨论】:

      【解决方案2】:

      你需要使用setState 来引起新的渲染

      添加

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

      然后更改它使用setAux(1)

      【讨论】:

        猜你喜欢
        • 2018-07-30
        • 1970-01-01
        • 1970-01-01
        • 2018-04-14
        • 2020-06-10
        • 1970-01-01
        • 2017-06-29
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多