react模态窗

本文介绍如何在React Native应用中实现模态窗口的功能,通过示例代码详细阐述设置和使用过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.导入modal在 react-native
import {Modal} from 'react-native';
2.modal 内容 可放在view最上层
<Modal
    // animationType={this.state.animationType}
    transparent={this.state.transparent}
    visible={this.state.modalVisible}
    onRequestClose={() => {
        this._setModalVisible(false)
    }}
    // onShow={this.startShow}
>
    <View style={styles.contView}>
        <View style={[styles.innerContainer, {width: width * 0.5, height: height * 0.4}]}>
            <TouchableOpacity style={styles.closeView}
                              onPress={this._setModalVisible.bind(this, false)}>
                <Image style={styles.closeImg}
                       source={{uri: config.SourceUrl + 'close.png'}}/>
            </TouchableOpacity>
            <Text style={styles.NowName}>{this.state.hintCode}</Text>
            <Text style={styles.NowText}>无查询结果!</Text>
        </View>
    </View>
</Modal>
3. 在构造函数中 设置默认状态 
constructor(props) {
    super(props);
    this.state = {
        modalVisible: false,//模态场景是否可见
        transparent: true,//是否透明显示
    }
}
4. 设置模态窗是否可见
//设置模态窗可见
_setModalVisible = (visible) => {
    this.setState({modalVisible: visible});
}

源码如下

import {Actions} from 'react-native-router-flux';
import {
    style,
    Sound,
    Component,
    cache,
    HttpRequest,
    HttpTask,
    qr,
    sleep,
    Lock,
    NetFileCache,
    $event, hex
} from 'jinghuan-react-native';
import DialogManager, {ScaleAnimation, SlideAnimation, DialogContent} from 'react-native-dialog-component';
import React from 'react';
import {
    Dimensions, PixelRatio, NativeModules, Platform, StyleSheet,
    Text, View, Image, Modal, Button, AppRegistry, TextInput,
    ImageBackground, TouchableOpacity, TouchableWithoutFeedback,
    ViewPagerAndroid, StatusBar, TouchableHighlight
} from 'react-native';
import styles from "./home.css"
import config from './utils/config'
import Products from './products'
import global from "./utils/global";
import in_array from "locutus/php/array/in_array";

import Pay from './pay'


let {height, width} = Dimensions.get('screen');
let TwoWidth = width / 2;

function timer(time) {

    return new Promise(function (resolve, reject) {
        console.log('Promise', time)
        setTimeout(() => {
            console.log(time)
            resolve()
        }, time);
    })
}

class Home extends Component {
    state = {
        qrcode: '',
        listType: 0,
        pay: false,
    };
    eventNames = ["Pager"]

    constructor(props) {
        super(props);
        this.state = {
            showModal: false,
            inputPwd: "",
            locked: true,
            // animationType: 'none',//none slide fade
            modalVisible: false,//模态场景是否可见
            transparent: true,//是否透明显示
            hintNum: 0,
            hintName: "",
            hintCode: ""
        }
    }

    pressNum(num) {
        var pwd = this.state.inputPwd;
        if ((pwd.length == 0 && num == 0) || pwd.length > 2)
            return

        this.setState({
            inputPwd: ((pwd + "" + num) * 1).toString(),
        });
        this.renderPwd();
    }

    setMenuNum = (num) => {
        this.setState({
            menuNum: num,
        });
    }


    deleteNum() {
        var pwd = this.state.inputPwd;
        pwd = pwd.substring(0, pwd.length - 1);
        this.setState({
            inputPwd: pwd,
        });
        this.renderPwd();
    }

    //确认编码点击事件
    async affirm() {
        if (this.state.inputPwd) {
            let {stocks, goods} = global;
            let code = this.state.inputPwd;
            let find = false;
            let name = "";

            for (let i in stocks) {
                let {goods_code, number, product_id, status} = stocks[i];

                if (goods_code.indexOf(code) != -1 && status === 0) {
                    // console.log(goods_code, number, product_id)
                    name = goods[product_id].name;
                    find = true;
                    if (number > 0) {
                        let val = goods[product_id];
                        this.pager.setPage(1);
                        this.products.show(val, code);
                        this.setState({inputPwd: ''})
                        return;
                    }
                }
            }
            if (!find) {
                this.setState({hintNum: 1});
                this.setState({hintCode: code});
                this.setState({modalVisible: true});
                // this.renderHint();
            } else {
                this.setState({hintNum: 2});
                this.setState({hintName: name});
                this.setState({modalVisible: true});
            }

        }

    }

    /**
     * 输编码提示
     * */
    renderHint() {
        if (this.state.hintNum === 1) {
            return (
                <Modal
                    // animationType={this.state.animationType}
                    transparent={this.state.transparent}
                    visible={this.state.modalVisible}
                    onRequestClose={() => {
                        this._setModalVisible(false)
                    }}
                    // onShow={this.startShow}
                >
                    <View style={styles.contView}>
                        <View style={[styles.innerContainer, {width: width * 0.5, height: height * 0.4}]}>
                            <TouchableOpacity style={styles.closeView}
                                              onPress={this._setModalVisible.bind(this, false)}>
                                <Image style={styles.closeImg}
                                       source={{uri: config.SourceUrl + 'close.png'}}/>
                            </TouchableOpacity>
                            <Text style={styles.NowName}>{this.state.hintCode}</Text>
                            <Text style={styles.NowText}>无查询结果!</Text>
                        </View>
                    </View>
                </Modal>
            )
        } else if (this.state.hintNum === 2) {

            return (
                <Modal
                    animationType={this.state.animationType}
                    transparent={this.state.transparent}
                    visible={this.state.modalVisible}
                    onRequestClose={() => {
                        this._setModalVisible(false)
                    }}
                    // onShow={this.startShow}
                >
                    <View style={styles.contView}>
                        <View style={[styles.innerContainer, {width: width * 0.5, height: height * 0.4}]}>
                            <TouchableOpacity style={styles.closeView}
                                              onPress={this._setModalVisible.bind(this, false)}>
                                <Image style={styles.closeImg}
                                       source={{uri: config.SourceUrl + 'close.png'}}/>
                            </TouchableOpacity>
                            <Text style={styles.NowName}>{this.state.hintName}</Text>
                            <Text style={styles.NowText}>该商品已售罄!</Text>
                        </View>
                    </View>
                </Modal>
            )
        }

    }

    //设置模态窗可见
    _setModalVisible = (visible) => {
        this.setState({modalVisible: visible});
    }


    //刷新编码状态
    renderPwd() {
        let inputPwd = this.state.inputPwd;
        return <View style={[styles.blackPoint, {width: TwoWidth - 150}]}><Text
            style={styles.inputText}>{inputPwd}</Text></View>;
    }


    /**
     * componentDidMount()在挂载结束之后马上被调用。需要DOM节点的初始化操作应该放在这里。
     */
    async componentDidMount() {

        // try {
        //     // 产品信息
        //     let qrcode = await HttpRequest('goods_list').getData();
        //
        //     console.log('+++++++++', qrcode);
        // } catch (e) {
        //     console.log(e);
        // }
    }

    render() {

        return (
            <View style={[styles.container, {width: width, height: height}]}>
                {this.renderHint()}
                {/*{this.renderHintTwo()}*/}
                <ViewPagerAndroid
                    ref={pager => this.pager = pager}
                    initialPage={0}
                    scrollEnabled={false}
                    style={[{
                        width,
                        height
                    }]}
                >
                    <View
                        style={[styles.totalView, {
                            width: width,
                            height: height
                        }]}>
                        <View style={[styles.leftContent, {width: width * 0.6, height: height}]}>
                            <ImageBackground style={styles.bgcImg} source={{uri: config.SourceUrl + 'bgc.jpg'}}>
                                <Text style={styles.product_code}>请输入产品编码</Text>
                                <View style={[styles.leftNumber, {width: width * 0.6, height: height - 200}]}>
                                    <View style={styles.InputView}>
                                        {this.renderPwd()}
                                    </View>
                                    <View style={[styles.numberBox, {width: width * 0.55}]}>
                                        <View style={styles.row}>
                                            <NumComp num="1" pressNum={() => this.pressNum(1)}/>
                                            <NumComp num="2" pressNum={() => this.pressNum(2)}/>
                                            <NumComp num="3" pressNum={() => this.pressNum(3)}/>
                                        </View>
                                        <View style={styles.row}>
                                            <NumComp num="4" pressNum={() => this.pressNum(4)}/>
                                            <NumComp num="5" pressNum={() => this.pressNum(5)}/>
                                            <NumComp num="6" pressNum={() => this.pressNum(6)}/>
                                        </View>
                                        <View style={styles.row}>
                                            <NumComp num="7" pressNum={() => this.pressNum(7)}/>
                                            <NumComp num="8" pressNum={() => this.pressNum(8)}/>
                                            <NumComp num="9" pressNum={() => this.pressNum(9)}/>
                                        </View>
                                        <View style={styles.row}>
                                            <NumComp num="删除" textStyle={{fontSize: 50, letterSpacing: 10}}
                                                     style={styles.affirm}
                                                     pressNum={() => this.deleteNum()}/>
                                            <NumComp num="0" pressNum={() => this.pressNum(0)}/>
                                            <NumComp num="确认" textStyle={{fontSize: 50, letterSpacing: 10}}
                                                     style={styles.affirm}
                                                     pressNum={() => this.affirm()}/>
                                        </View>
                                    </View>
                                </View>
                            </ImageBackground>
                        </View>
                        <View
                            style={[styles.rightContent, {width: width * 0.4, height: height}]}>
                            <TouchableOpacity style={styles.floatView} activeOpacity={0.8} onPress={async () => {
                                this._emit("Pager.set", 1);
                                this.handlerSelected()
                                // this.state.listType = 2;
                                // console.log('1',this.state.listType );
                            }}>
                                <View style={[styles.Pview, {width: width * 0.3}]}>
                                    <Text style={styles.Ptext}>自选产品购买</Text>
                                    <Image style={styles.arrowsImg}
                                           source={{uri: config.SourceUrl + 'rightArrows.png'}}/>
                                </View>
                            </TouchableOpacity>
                            {this.renderManager()}
                            <View style={styles.service}>
                                <Text style={styles.bottomText}>服务热线: </Text>
                                <Text style={styles.androidText}>400-966-8700</Text>
                            </View>
                        </View>
                    </View>

                    <View style={{width: width, height: height}}>
                        <Products ref={products => this.products = products}/>
                    </View>
                    {/*支付*/}
                    {/*<View style={[styles.returnBgc, {width: width, height: height}]}>*/}
                    {/*    <Pay ref={pay => this.pay = pay} onOut={(stock) => {*/}
                    {/*        this.setState({stock})*/}
                    {/*        // this._emit("Pager.set", 0);*/}
                    {/*        this.pager.setPage(2);*/}
                    {/*        this.timer.play(10);*/}
                    {/*        this.pay.hide()*/}
                    {/*    }}/>*/}
                    {/*</View>*/}
                </ViewPagerAndroid>
            </View>
        );
    }

    renderManager() {
        return (

            <View style={[styles.YGview, {width: width * 0.4}]}>

                <TouchableWithoutFeedback style={styles.weixinImg} onLongPress={

                    async () => {
                        // try {
                        //     let token = await HttpRequest('token').getData();
                        //
                        //     if (token && token.token && token.url) {
                        //         this.state.token = token.token;
                        //
                        //         let qrbase64 = await qr(token.url, {size: 200});
                        //         if (this.state.page == 0) {
                        //             DialogManager.show({
                        //                 width: 240,
                        //                 height: 240,
                        //                 //title: 'Dialog',
                        //                 titleAlign: 'center',
                        //                 animationDuration: 200,
                        //                 ScaleAnimation: new ScaleAnimation(),
                        //                 //dialogAnimation: new SlideAnimation({slideFrom: 'bottom'}),
                        //                 children: (
                        //                     <DialogContent>
                        //                         <Image style={styles.dialog} source={{uri: qrbase64}}></Image>
                        //                     </DialogContent>
                        //                 ),
                        //                 onDismissed: () => {
                        //                     this.state.token = null;
                        //                 }
                        //             }, () => {
                        //
                        //             });
                        //         }
                        //     } else {
                        //         alert("网络异常")
                        //     }
                        // } catch (e) {
                        //     console.log(e);
                        // }

                        Actions.manager()
                    }}>
                    <Image style={styles.YGimg} source={{uri: config.SourceUrl + 'ygLogo.png'}}/>
                </TouchableWithoutFeedback>
            </View>
        )
    }

    @$event("Pager.set")
    handlerEventPagerSet = (page) => {
        this.pager.setPage(page);
    }

    handlerSelected = () => {
        this.products.show();
    }
}

class NumComp extends Component {
    render() {
        return (
            <View style={[styles.gridView]}>
                <TouchableOpacity activeOpacity={0.1} onPress={this.props.pressNum}>
                    <View style={[styles.cycle, this.props.style]}>
                        <Text style={[styles.numText, this.props.textStyle]}>{this.props.num}</Text>
                    </View>
                </TouchableOpacity>
            </View>
        )
    }
}


export default Home

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值