【问题标题】:React native button need twice click to change stateReact 本机按钮需要两次单击才能更改状态
【发布时间】:2020-08-09 03:34:20
【问题描述】:

当我单击“显示元素”按钮时,我想将状态更改为 true 当我点击“隐藏元素”按钮时,我想将状态更改为 false

但是当我第一次单击“显示元素”按钮时,它不会更改为 true,并且需要我第二次单击按钮才能将状态更改为 true。当我点击“隐藏元素”按钮时也是如此

这是我的代码:

import * as React from 'react';
import { View, Text, StyleSheet, Platform, AsyncStorage, TouchableHighlight, ScrollView, SafeAreaView, Button  } from 'react-native'

class Base extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      isForShowVar: true
    }
  }

  render() {
    return(
      <View>
        <Button
            style={{marginTop:50, width:150}}
            title="Hide Element"
            onPress={()=>{ alert(this.state.isForShowVar); this.setState({isForShowVar: false});  }}
          />  
          <Button
            style={{marginTop:50, width:150}}
            title="Show Element"
            onPress={()=>{ alert(this.state.isForShowVar); this.setState({isForShowVar: true});  }}
          />  
      </View>
    )
  }
}

export default Base;

你可以在here测试代码

当我第一次点击按钮时如何改变状态?

谢谢

【问题讨论】:

    标签: react-native state


    【解决方案1】:

    Ciao,这是因为您在设置之前阅读了isForShowVar。无论如何,如果您在this.setState 之后移动警报,您将获得旧值,因为this.setState 是异步的。但是你可以像这样使用this.setState 回调:

    this.setState({isForShowVar: true}, () => {
       alert(this.state.isForShowVar); 
    });
    

    Here您的代码已修改。

    【讨论】:

    • 感谢您的解决方案,我只是使用警报来显示单击按钮时发生的情况,我更新了我的问题,请查看链接:snack.expo.io/@mojtaba.expo/card.actions
    • 对不起,我不明白。你提出了一个问题。我回答了。答案正确吗?如果是,则将其标记为有效。然后,如果你想要更多,你可以在这里问我其他的事情。无论如何,您的新示例尚不清楚。您已经将this.state.isForShowVar 作为道具传递给FadeInOut 组件...
    猜你喜欢
    • 1970-01-01
    • 2022-07-01
    • 2021-02-26
    • 2022-07-08
    • 1970-01-01
    • 2017-09-23
    • 2014-08-08
    • 1970-01-01
    • 2019-05-30
    相关资源
    最近更新 更多