如何在react native中显示吐司消息

dw1jzc5e  于 2023-05-23  发布在  React
关注(0)|答案(5)|浏览(161)

我正在尝试在react native中显示吐司消息,单击按钮

import React,{ Component } from 'react';
import { StyleSheet,TextInput, View, Button, Text, ToastAndroid } from 'react-native';

export default class App extends Component {

  state = {
              placeName : "",
              titleText: "Text view"
          }

  placeNameChangeHandler = val =>{
   this.setState({
     placeName : val
   })
  }

  placeSubmitHandler = () =>{
    this.setState({
      titleText: this.state.placeName.trim() 

    })
  }

   render() {
      return (
      <View style={styles.rootContainer}>

        <View style={styles.btnEditContainer}>
          <View style ={styles.wrapStyle}>
          <TextInput
          style = {styles.textInputStyle}
          value = {this.state.placeName}
          onChangeText = {this.placeNameChangeHandler}
          />
        </View>
          <View style ={styles.wrapStyle}>
          <Button
          title="Add"
          style ={styles.buttonStyle}
          onPress ={this.placeSubmitHandler}/>
        </View>
        </View>

        <View style={styles.textContainer}>
          <View style ={styles.wrapStyle}>
            <Text
            style ={styles.textStyle}>
            {this.state.titleText}
            </Text>
          </View>
        </View>

        </View>
      );
   }
}

const styles = StyleSheet.create({
  rootContainer: {
    height:"100%",
    width:"100%",
    backgroundColor: "#008000",
    flexDirection:"column",
    alignItems:"center",
    justifyContent: "center"
  },
  btnEditContainer: {
    backgroundColor:"#008080",
    flexDirection:"row",
    alignItems:"center",
    justifyContent: "center"
  },
  textContainer: {
    backgroundColor:"#00FFFF",
    flexDirection:"column",
    alignItems:"center",
    justifyContent: "center"
  },
  textStyle: {
    fontSize: 20,
    flexDirection:"column",
    alignItems:"center",
    justifyContent: "center"
  },
  buttonStyle: {
  },
  textInputStyle: {
    borderColor:"black",
    borderWidth:1,
  },
  wrapStyle: { marginLeft:5,
    marginRight:5 },
});
eqoofvh9

eqoofvh91#

可以使用下面的notifyMessage来显示吐司消息:

import {
      ToastAndroid,
      Platform,
      AlertIOS,
    } from 'react-native';

function notifyMessage(msg: string) {
  if (Platform.OS === 'android') {
    ToastAndroid.show(msg, ToastAndroid.SHORT)
  } else {
    AlertIOS.alert(msg);
  }
}


在iOS和Android中使用react-native-simple-toast

import Toast from 'react-native-simple-toast';

Toast.show('This is a toast.');
Toast.show('This is a long toast.', Toast.LONG);
vfwfrxfs

vfwfrxfs2#

React Native现在有内置的API Alert,可以在iOS和Android上运行。https://reactnative.dev/docs/alert

kkbh8khc

kkbh8khc3#

为这个定制的吐司创建一个单独的组件,并在其中使用以下代码:

import React, {
     useState, 
    useImperativeHandle,
     forwardRef,
     useRef } from "react";
import {
      Text,
      StyleSheet,
      Animated,
      Platform,
      UIManager,
    } from "react-native";
    
    if (
      Platform.OS === "android" &&
      UIManager.setLayoutAnimationEnabledExperimental
    ) {
      UIManager.setLayoutAnimationEnabledExperimental(true);
    }
    
    const Toast = (props, ref) => {
      const [showToast, setShowToast] = useState(false);
      const fadeAnim = useRef(new Animated.Value(0)).current;
    
      const toast = () => {
        if (!showToast) {
          setShowToast(true);
          Animated.timing(fadeAnim, {
            toValue: 1,
            duration:500,
            useNativeDriver: true,
          }).start();
          setTimeout(() => {
            Animated.timing(fadeAnim, {
              toValue: 0,
              duration: 500,
              useNativeDriver: true,
            }).start(() => {
              setShowToast(false);
            });
          }, 3000); 
        }
      };
    
      useImperativeHandle(ref, () => ({
        toast,
      }));
    
      if (showToast) {
        return (
          <Animated.View style={[styles.toastContainer, { opacity: fadeAnim }]}>
            <Text style={styles.toastText}>{props.message}</Text>
          </Animated.View>
        );
      } else {
        return null;
      }
    };
    
    const styles = StyleSheet.create({
      container: {
        position: "absolute",
        borderRadius: 30,
        overflow: "hidden",
        flexDirection: "row",
        bottom: 20,
        right: 20,
        alignItems: "center",
        justifyContent: "center",
      },
      toastContainer: {
        backgroundColor: "#292929",
        borderRadius: 10,
        padding: 10,
        position: "absolute",
        bottom: 100,
        alignSelf: "center",
      },
      toastText: {
        color: "white",
        fontSize: 14,
      },
    });
    
    export default forwardRef(Toast);

并从所需的组件调用它;供您参考:

const ToastRef = useRef(null);
     const showToast = () => {
        ToastRef.current.toast();
      };

    <Toast ref={ToastRef} message="Hello World!" />
8dtrkrch

8dtrkrch4#

如果你正在寻找一个简单的,JS唯一的实现吐司通知的React Native,它可以在iOS和Android上工作,你可以看看
https://github.com/jeanverster/react-native-styled-toast
用途:

import { useToast } from 'react-native-styled-toast'

const { toast } = useToast()

return <Button onPress={() => toast({ message: 'Check me out!', ...config })} />
mfpqipee

mfpqipee5#

您也可以使用包吐司消息。检查react-native-toast-message

相关问题