react-native-root-toast的使用

給大家安利一款可以在iosandroid上通用的Toast組件: react-native-root-toast
現在開源的Toast組件一大堆,為什么要選用這個呢?原因如下:

  • javascript解決方案,免去了原生安裝的各種繁雜步驟,直接一行npm install react-native-root-toast --save搞定
  • 同時兼容iOSAndroid,使用完全一致的接口,不用再為同時兼容兩個平臺再寫額外的代碼
  • 可以自定義toast的各類屬性(顯示時間、位置、延時、動畫、陰影等)
  • 同時支持兩種調用形式(可以使用API調用,也可以作為Component直接放在render里面進行控制)

安裝

npm install [React](http://lib.csdn.net/base/react)-native-root-toast --save

搞定!

使用

可以支持兩種不同的調用方式.

如果你喜歡API方式的調用

import Toast from 'react-native-root-toast'; // 引入類庫

// 通過調用 Toast.show(message, options); 可以在屏幕上顯示一個toast,并返回一個toast實例
let toast = Toast.show('This is a message', {
    duration: Toast.durations.LONG, // toast顯示時長
    position: Toast.positions.BOTTOM, // toast位置
    shadow: true, // toast是否出現陰影
    animation: true, // toast顯示/隱藏的時候是否需要使用動畫過渡
    hideOnPress: true, // 是否可以通過點擊事件對toast進行隱藏
    delay: 0, // toast顯示的延時
    onShow: () => { 
        // toast出現回調(動畫開始時)
    },
    onShown: () => {
        // toast出現回調(動畫結束時)
    },
    onHide: () => {
        // toast隱藏回調(動畫開始時)
    },
    onHidden: () => {
        // toast隱藏回調(動畫結束時)
    }
});

// 也可以通過調用Toast.hide(toast); 手動隱藏toast實例
setTimeout(function () {
    Toast.hide(toast);
}, 500);

你也可以通過react組件方式調用Toast.
render里面加入<Toast />組件,并通過visible屬性對Toast進行控制.
<Toast />的屬性和API調用時傳入的選項相同.toast內容添加在元素內部:<Toast>message</Toast>

注意:通過組件方式調用的toast,在<Toast />組件 componentWillUnmount 的時候會自動消失

import React, {Component} from 'react-native';
import Toast from 'react-native-root-toast';

class Example extends Component{
    constructor() {
        super(...arguments);
        this.state = {
            visible: false
        };
    }

    componentDidMount() {
        setTimeout(() => this.setState({
            visible: true
        }), 2000); // show toast after 2s

        setTimeout(() => this.setState({
            visible: false
        }), 5000); // hide toast after 5s
    };

    render() {
        return <Toast
            visible={this.state.visible}
            position={50}
            shadow={false}
            animation={false}
            hideOnPress={true}
        >This is a message</Toast>;
    }
}

報錯 null is not an object(evaluting '_this._root_setNativeProps')

修改方法:
在源文件lib/ToastContainer.js中改下代碼

componentWillUnmount = () => {
   this._root&&this._hide();
};

參考:
http://blog.csdn.net/sinat_17775997/article/details/60954255
https://github.com/magicismight/react-native-root-toast/issues/24

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容