自定义ReactNative Toast组件

754 阅读1分钟

虽然有各种第三方的Toast库可以使用,要么过于复杂花哨,要么需要注入根组件App.js(纯属个人不喜欢,也没有什么不好)。索性就自定义一个吧,供大家参考:

首先,创建一个名为CustomToast.js的文件并定义一个CustomToast组件

import React, { useEffect, useState } from 'react';
import { Animated, StyleSheet, Text, View } from 'react-native';

const CustomToast = ({ message, duration = 2000, onDismiss }) => {
  const [fadeAnim] = useState(new Animated.Value(0));

  useEffect(() => {
    Animated.timing(fadeAnim, {
      toValue: 1,
      duration: 200,
      useNativeDriver: true,
    }).start();

    const timer = setTimeout(() => {
      onDismiss();
    }, duration);

    return () => {
      clearTimeout(timer);
    };
  }, []);

  return (
    <Animated.View style={[styles.toast, { opacity: fadeAnim }]}>
      <Text style={styles.toastText}>{message}</Text>
    </Animated.View>
  );
};

const styles = StyleSheet.create({
  toast: {
    position: 'absolute',
    top: '50%',
    left: '50%',
    transform: [{ translateX: -50 }, { translateY: -50 }],
    paddingHorizontal: 12,
    paddingVertical: 8,
    backgroundColor: 'rgba(0, 0, 0, 0.8)',
    borderRadius: 8,
  },
  toastText: {
    color: '#ffffff',
  },
});

export default CustomToast;

接下来,在需要显示提醒的组件中,导入CustomToast组件,并使用状态来控制其显示与隐藏。

import React, { useState } from 'react';
import { TouchableOpacity, Text, View } from 'react-native';
import CustomToast from '../components/CustomToast';

const MyComponent = () => {
  const [showToast, setShowToast] = useState(false);

  const handleShowToast = () => {
    setShowToast(true);
  };

  const handleDismissToast = () => {
    setShowToast(false);
  };

  return (
    <View style={{ flex: 1 }}>
      <TouchableOpacity onPress={handleShowToast}>
        <Text>复制</Text>
      </TouchableOpacity>
      {showToast && (
        <CustomToast
          message="复制成功"
          duration={1500}
          onDismiss={handleDismissToast}
        />
      )}
    </View>
  );
};

export default MyComponent;

效果图:

image.png