如何在本机反应中显示吐司消息

Dev*_*ath 19 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 },
});
Run Code Online (Sandbox Code Playgroud)

Roc*_*cky 46

可以在下面使用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);
  }
}
Run Code Online (Sandbox Code Playgroud)

或者

使用react-native-simple-toast两个iOS和Android系统。

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

Toast.show('This is a toast.');
Toast.show('This is a long toast.', Toast.LONG);
Run Code Online (Sandbox Code Playgroud)

  • 使用“Alert”而不是“AlertIOS”,因为“AlertIOS”已弃用。 (6认同)
  • 后者会在 ios 中抛出错误(至少对我来说) (3认同)
  • 您现在可以在 Android 和 iOS 上使用“Alert”:https://reactnative.dev/docs/alert (2认同)