如何以编程方式删除警报提示?

IT技术 javascript reactjs react-native react-native-android react-native-ios
2021-05-16 19:13:44

单击按钮后,我会开始一个需要一些时间的过程,一旦完成,我就会导航到指定的屏幕。

在处理过程中,我会根据文档显示Alert“正在加载”提示:“默认情况下,唯一的按钮将是“确定”按钮”一旦该过程完成,我再次提醒数据已准备就绪。

问题是我得到了两个相互重叠的提示,并且它们需要用户的点击才能被删除。

我想在显示第二个提示之前删除第一个提示(并且可能为第二个设置一个计时器,然后也将其删除)。

如何以Alert编程方式删除提示?

1个回答

为了实现您的要求,一个基本的解决方法是创建一个单独的组件来代替警报。

我编写的组件接受两个props。textvisible

在您的屏幕内,您可以将其添加为:

import React from 'react'
[....]

export default class Screen extends React.Component {
  state = {
    visible: true,
    text: "Loading... Please wait"
  }

  drawAlert() {
    setTimeout(() => {
      this.setState({text: "Will dismiss in 1 second"}, () => {
        setTimeout(() => {
          this.setState({visible: false})
        }, 1000);
      })
    }, 4000); // fake API request
    return (
      <Alert text={this.state.text} visible={this.state.visible} />
    )
  }

  render() {
    return(
      <Alert text={this.state.text} visible={this.state.visible} />
    )
  }
}

这是alert组件

import React, { Component } from 'react'
import { View, TouchableOpacity, Text } from 'react-native'

export default class Alert extends Component {
  state = {
    text: this.props.text,
    visible: this.props.visible
  }

  componentWillReceiveProps(nextProps) {
    this.setState({text: nextProps.text, visible: nextProps.visible})
  }

  drawBox() {
    if (this.state.visible) {
      return(
        <View style={styles.container}>
          <View style={styles.boxContainer}>
            <View style={styles.textContainer}>
              <Text style={styles.text}>{this.state.text}</Text>
            </View>
            <TouchableOpacity onPress={this.props.onPress} style={styles.buttonContainer}>
              <Text style={styles.buttonText}>OK</Text>
            </TouchableOpacity>
          </View>
        </View>
      )
    }
  }

  render() {
    return(
      <View style={styles.container}>
        {this.drawBox()}
      </View>
    )
  }
}

const styles = {
  wrapper: {
    flex: 1,
  },
  container: {
    zIndex: 99999,
    position: "absolute",
    backgroundColor: "rgba(0, 0, 0, 0.1)",
    top: 0,
    left: 0,
    right: 0,
    bottom: 0,
    justifyContent: 'center',
    alignItems: 'center',
  },
  boxContainer: {
      backgroundColor: "#FFF",
      borderRadius: 2,
      padding: 10,
      width: 300,
      borderColor: "rgba(0,0,0,.1)",
      borderBottomWidth: 0,
      shadowOffset: { width: 0, height: 2 },
      elevation: 1,
      padding: 20
  },
  textContainer: {
    marginBottom: 20
  },
  text: {
    color: "#424242",
    fontFamily: "Roboto",
    fontSize: 18
  },
  buttonContainer: {
    alignItems: 'flex-start'
  },
  buttonText: {
    color: "#009688"
  }
}

希望能帮助到你。