• React Native =>(箭头函数)


    我们经常会在代码中发现=>(箭头函数),那么什么是箭头函数呢?

    其实箭头函数类似iOS的block(回调),安卓的回调,JS的匿名函数(简化了函数定义)

    简介:

    ES6标准新增了一种新的函数:Arrow Function(箭头函数)。

    所以你的浏览器首先要支持ES6的Arrow Function。

    为什么叫Arrow Function?因为它的定义用的就是一个箭头:

    x => x * x

    上面的箭头函数相当于:

    function (x) {
        return x * x;
    }

    箭头函数相当于匿名函数,并且简化了函数定义。

    箭头函数有两种格式

    A:只包含一个表达式,连{ ... }return都省略掉了

    var fn = x => x * x;

    B:还有一种可以包含多条语句,这时候就不能省略{ ... }return

    x => {
        if (x > 0) {
            return x * x;
        }
        else {
            return - x * x;
        }
    }

    详情参考:https://www.liaoxuefeng.com/wiki/1022910821149312/1031549578462080

    示例:

    1、TouchableOpacity的onPress属性

                        <TouchableOpacity onPress={() => {
                            this.hotMenueAlert.setModalVisible(true)
                        }}>
                            <View style={style.item_center_right_bg}>
                                
                            </View>
                        </TouchableOpacity>

    2、组件的ref属性,通过这个属性我们可以将组件赋给成员变量来全局保存

                    <RoleHotModalMenu
                        // 组件的ref属性,返回组件本身
                        ref={(c) => {
                            if (c != null) {
                                this.hotMenueAlert = c;
                            }
                        }}/>

    3、props属性

    定义:

    export interface IProps extends IBasePageProp {
        onClickCancle?: (that: any) => void,
        onClickDone: (that: any, hotName: string) => void,
        data: string[],
        currentselhotName: string,
    }

    赋值:

                    <RoleHotModalMenu
                        
                        data={['全部', '5', '4', '3', '2', '1']}
                        // 自定义onClickDone属性赋值
                        onClickDone={(that: any, hotName: string) => {
                            that.setModalVisible(false);
                            this.setState({ hotname: hotName }, () => {
                                this.chanceditailslist?.resetPageData();
                            })
                        }}
    
                        currentselhotName={this.currentselhotname()}
    
                    />

    使用:

    this.props.onClickDone(this, this.state.hotName);

    4、成员变量

    定义:

    onPress!: () => void;// 无参无返回值
    format: ((labels: string[]) => string) | undefined;// 参数数组,返回值是字符串
    onOk: ((value: any) => void) | undefined; // 参数any、无返回值

    赋值:

            this.onPress = () => {
                this.setState({
                    data: datacity,
                });
            };
    
            this.onOk = value => {
                this.setState({ value }, () => {
                    this.setState({ lables: this.lables }, () => {
                        this.chanceditailslist?.resetPageData();
    
                    })
                });
    
            };
    
            this.format = (labels: string[]) => {
                let kk = labels.join(' ')
                this.lables = labels
                if (kk && kk.length) {
                    return kk
                } else {
                    return '工作地'
                }
    
    
            };

    使用:

    <Picker
                            data={datacity}
                            cols={2}
                            format={this.format}
                            value={this.state.value}
                            onOk={this.onOk}
                            title={<Text style={style.topView_title}>选择工作地</Text>}
                            okText={<Text style={style.topView_buttonText}>确定</Text>}
                            dismissText={<Text style={style.topView_buttonText}>取消</Text>}
                        >

    备注:

    示例代码,

    1、涉及箭头函数

    2、UI组件做成员变量(通过组件的ref属性回调获取到组件对象然后赋值给成员变量)、

    复制代码
    // 其实也是箭头函数
    ref={(c) => { if (c != null) { this.hotMenueAlert = c; } }}
    复制代码

    3、通过props访问成员变量

    4、本地json文件引入

    5、不论是props、state、还是成员变量都指向了property

    state

     // (property) IState.datatop: ResultList 读写(会触发UI刷新)
        datatop: ResultList,

    props

    // (property) IProps.ce: number  只读
          ce:number;

    成员变量

    // (property) default.orgId: number 读写 不会触发UI变化
        orgId!: number
    复制代码
    // 本地json文件
    const datacity = require('./city.json')
    
    // 组件也可以这样写箭头函数
    const CustomChildren = (props) => (
        // 调用成员变量onPress,(之所以能通过props调用是因为成员变量属于默认属性(个人理解)(property) default.onPress: () => void),而直接写在props中的(通过this.props.ce访问)是只读的
        <TouchableOpacity onPress={props.onPress}>
            <View style={style.item_center_left_bg}>
                {showtext(props.extra)}
                <Image style={style.item_right_img} source={require('../../image/pack_back.png')} />
                
    
            </View>
        </TouchableOpacity>
    );
    
    //  方法
    function showtext(exstra: string) {
    
        if (exstra && exstra == '工作') {
            return (
                <Text style={style.item_left_title} numberOfLines={1}>{exstra}</Text>
            )
    
        } else {
            return (
                <Text style={style.item_blue_title} numberOfLines={1}>{exstra}</Text>
            )
    
        }
    }
    
    // 机会详情选择组织通知
    const chancedetailsViewCallback = 'chancedetailsViewCallback'
    export interface IState {
        // (property) IState.datatop: ResultList 读写(会触发UI刷新)
        datatop: ResultList,
        data: [],
        value: string[],
        hotname: string,
        lables: string[]
    }
    
    export interface IProps extends IBasePageProp {
        // (property) IProps.ce: number  只读
          ce:number;
    }
    
    interface INoticeInfo extends IBaseNativeNotice {
        InfoArray: addressBookItem[],
    }
    
    interface addressBookItem {
        oId: string,
    }
    
    export default class extends UtilsRootPage<IProps, IState> {
    
        // ------成员变量------
        // 数据类型
        // (property) default.orgId: number 读写 不会触发UI变化
        orgId!: number
        lables!: string[]
        // 箭头函数(iOS的block、回调,安卓的回调)(箭头函数相当于匿名函数,并且简化了函数定义)
        // (property) default.onPress: () => void 读写
        onPress!: () => void;// 无参无返回值
        format: ((labels: string[]) => string) | undefined;// 参数数组,返回值是字符串
        onOk: ((value: any) => void) | undefined; // 参数any、无返回值
        // UI组件
        chanceditailslist!: ComponentChanceDetialsList | null;
        private hotMenueAlert!: RoleHotModalMenu;
        // ------成员变量------
    
        static navigationOptions: IAirNavigationOption = ({ navigation }) => {
            return {
                title: '详情',
            }
        }
    
        subPageLoad() {
            this.loadData()
        }
    
        subPageInit() {
            
            // ---成员变量赋值---
            let orgId = parseInt(UtilsSuperGuide.getInstance().navigationParam(this, "orgId"));
            this.orgId = orgId
    
            this.onPress = () => {
                this.setState({
                    data: datacity,
                });
            };
    
            this.onOk = value => {
                this.setState({ value }, () => {
                    this.setState({ lables: this.lables }, () => {
                        this.chanceditailslist?.resetPageData();
    
                    })
                });
    
            };
    
            this.format = (labels: string[]) => {
                let kk = labels.join(' ')
                this.lables = labels
                if (kk && kk.length) {
                    return kk
                } else {
                    return '工作地'
                }
    
    
            };
    
           // ---成员变量赋值---
    
           //  state 初始化
           this.state = {
            datatop: {} as ResultList,
            data: [],
            value: [],
            hotname: '角色热度',
            lables: []
        }
    
            //  添加通知
            UtilsSuperBridge.getInstance().noticeAddLisenter(chancedetailsViewCallback, this.addressBookCallBack.bind(this));
    
        }
    
        subPageUnmount() {
            // 移除通知
            UtilsSuperBridge.getInstance().noticeRemoveLisenter(chancedetailsViewCallback);
        }
    
        subPageRender() {
            return (
                <View style={style.container}>
                    {/* 弹出菜单 */}
                    <RoleHotModalMenu
                    // UI组件赋值:this.hotMenueAlert = c;
                        ref={(c) => {
                            if (c != null) {
                                this.hotMenueAlert = c;
                            }
                        }}
                        data={['全部', '5', '4', '3', '2', '1']}
                        onClickDone={(that: any, hotName: string) => {
                            that.setModalVisible(false);
                            this.setState({ hotname: hotName }, () => {
                                // 调用this.chanceditailslist
                                this.chanceditailslist?.resetPageData();
                            })
    
                        }}
    
                        currentselhotName={this.currentselhotname()}
    
                    />
    
                    {/* 选择组件 */}
                    <View style={style.item_center_bg}>
                        {/* 地区选择 */}
                        <Picker
                            data={datacity}
                            cols={2}
                            format={this.format}
                            value={this.state.value}
                            onOk={this.onOk}
                            title={<Text style={style.topView_title}>选择工作地</Text>}
                            okText={<Text style={style.topView_buttonText}>确定</Text>}
                            dismissText={<Text style={style.topView_buttonText}>取消</Text>}
                        >
                            <CustomChildren></CustomChildren>
    
                        </Picker>
    
                        {/* 角色热度选择 */}
                        <TouchableOpacity onPress={() => {
                            // 调用this.hotMenueAlert
                            this.hotMenueAlert.setModalVisible(true)
                        }}>
                            <View style={style.item_center_right_bg}>
                                <Text style={this.showstyle()} numberOfLines={1}>{this.state.hotname}</Text>
                                <Image style={style.item_right_img} source={require('../../image/pack_back.png')} />
    
                            </View>
                        </TouchableOpacity>
                    </View>
    
                    {/* 列表 */}
                    <ComponentChanceDetialsList
                        hotname={this.state.hotname}
                        lables={this.state.lables}
                        orgPath={this.state.datatop.orgPath}
                        // 成员变量UI组件赋值:this.chanceditailslist = chanceditailslist
                        ref={chanceditailslist => {
                            this.chanceditailslist = chanceditailslist;
                        }}
                    />
    
                </View>
    
            );
        }
    
        private addressBookCallBack(info: INoticeInfo) {
    
            // UtilsSuperCommon.logWarn(info.InfoArray);
            let array: string[] = [];
            let infoArray = info.InfoArray
            for (const addressBookItem of infoArray) {
                if (addressBookItem.oId !== null) {
                    array.push(addressBookItem.oId)
                }
            }
            if (array !== null) {
                this.orgId = parseInt(array[0])
                // console.warn(this.orgId)
                this.lables = []
                this.setState({ hotname: '全部' ,value: ['0'],lables: []}, () => {
                    this.loadData()
                })
    
            }
        }
    
        //  热度样式
        private showstyle() {
            if (this.state.hotname == '热度') {
                return (style.item_left_title)
            } else {
                return (style.item_blue_title)
    
            }
        }
    //  详情信息
        private loadData() {
    
            ServicesApiChance.chancedetails(this.orgId).then(res => {
                // console.warn(res);
                if (res.code == 200) {
                    if (null != res.data) {
                        this.setState({ datatop: res.data }, () => {
                            this.chanceditailslist?.resetPageData()
                        })
                    }
    
                } else {
                    Toast.info(res.message, 1)
                }
            })
    
        }
    
    }
    
    const style = StyleSheet.create({
    
        container: {
            backgroundColor: ThemeAheadGlobal.colorBaseBackCommon,
            flex: 1
        },
    
        list: {
            flex: 1
        },
    
        item_center_bg: {
            backgroundColor: 'transparent',
            flexDirection: 'row',
            marginHorizontal: 10,
            marginBottom: 3,
            marginTop: 15,
        },
    
        item_center_left_bg: {
            backgroundColor: '#FFFFFF',
            flexDirection: 'row',
            alignItems: 'center',
            borderRadius: 4,
             (DeviceHelp.getDeviceWidth() - 35) * 0.5
        },
    
        item_center_right_bg: {
            backgroundColor: '#FFFFFF',
            flexDirection: 'row',
            alignItems: 'center',
            borderRadius: 4,
             (DeviceHelp.getDeviceWidth() - 35) * 0.5,
            marginLeft: 15,
        },
    
        item_right_img: {
            marginLeft: 10,
            marginRight: 15,
             15,
            height: 15,
        },
    
        item_left_title: {
            fontSize: DeviceHelp.fontSize(14),
            color: '#999999',
            marginLeft: 15,
            marginVertical: 10,
            flex: 2,
        },
    
        item_blue_title: {
            fontSize: DeviceHelp.fontSize(14),
            color: '#3480FF',
            marginLeft: 15,
            marginVertical: 10,
            flex: 2,
        },
    
        topView_buttonText: {
            fontSize: 16,
            color: ThemeAheadGlobal.colorBaseHighLight,
        },
    
        topView_title: {
            fontSize: 16,
            color: ThemeAheadGlobal.colorBaseFontCommon,
        },
    
    
    })
    复制代码
  • 相关阅读:
    MasterPage中找尋控件
    Win2003服务器发布的网站Session经常丢失
    Toolkits
    aspnet_regiis 命令格式說明
    SQL转换数字中文大写
    ASP.NET2.0实现无刷新客户端回调
    SQL的使用规范
    pku3207 2SAT问题入门
    unity3d打包资源
    Vector3.Lerp 插值
  • 原文地址:https://www.cnblogs.com/lijianyi/p/14926090.html
Copyright © 2020-2023  润新知