如何在 React Native 中使用自定义警报?

How to use custom alert in React Native?

我在 React Native 中创建了一个自定义警报作为组件。我使用 Modal 创建了这个自定义警报。我的问题是,如何使用它?我不想在 React Native 中使用 Alert.alert,而是想显示我自己的警报。

这是我的 Custom Alert Modal.

import React, { Component } from 'react';
import { Text, View } from 'react-native';
import Modal from 'react-native-modal';

import styles from './style';
import Button from '../../components/Button';

export default class CustomAlert extends Component {

  renderModalContent = () => (
    <View style={styles.content}>
      <Text style={styles.contentTitle}>{this.props.title}</Text>
      <Text style={styles.contentInfo}>{this.props.content}</Text>
      <View style={styles.buttonContainer}>
        <Button
          color={this.props.buttonColor}
          text={this.props.buttonText}
          onPress={this.props.buttonOnPress}
        />
      </View>
    </View>
  );

  render() {
    return (
      <View style={styles.container}>
        <Modal
          isVisible={this.props.isVisible}
          backdropColor="#000000"
          backdropOpacity={0.9}
          animationIn="zoomInDown"
          animationOut="zoomOutUp"
          animationInTiming={600}
          animationOutTiming={600}
          backdropTransitionInTiming={600}
          backdropTransitionOutTiming={600}
        >
          {this.renderModalContent()}
        </Modal>
      </View>
    );
  }
}

这就是我想要使用它的方式。我想通过一个函数显示这个警报。这意味着当函数遇到错误时,我想显示我的自定义警报。

myFunction()
  .then(() => // do something)
  .catch(() => // show my custom alert);

你能帮我解决这个问题吗?

在你的 catch 块中设置 isVisible 为真。

myFunction()
 .then(() => // do something)
 .catch((e) => this.setState({ isVisible: true }))