• react-native 组件之间传值


    1.通过 AsyncStorage 将值保存在本地(最低端的方法)

    import {
        AsyncStorage,
    } from 'react-native';
    
    // 保存 IP
    AsyncStorage.setItem('LoginIP',new_value);
    
    // 获取IP
    let ApiBase;
    AsyncStorage.getItem('LoginIP')
        .then((value) => {
            that.setState({
                ApiBase: value
            });
        });
    

    2.定义成员属性 通过 props 传值(父组件向子组件传值)

    CommunalCell.js

    定义成员属性 接收外部传值

    /**
     * Cell
     */
    import React, { Component } from 'react';
    import {
        StyleSheet,
        Text,
        View,
    } from 'react-native';
    
    import PropTypes from 'prop-types';
     
    export default class CommunalCell extends Component {
     
        // 定义成员属性
        static propTypes = {
            name:PropTypes.string,
            gender:PropTypes.string,
        };
     
        render() {
            return (
                <View>
                    <Text>姓名:{this.props.name}</Text>
                    <Text>姓名:{this.props.gender}</Text>
                </View>
            );
        }
    }
     
    const styles = StyleSheet.create({
    
    });
    

    引用 传值

    // 引入 cell
    import CommunalCell from '../main/CommunalCell';
    
    // 返回每一行cell的样式
    renderRow(rowData) {
        // 使用cell组件
        return(
            <CommunalCell
                name={rowData.name}
                gender={rowData.gender}
            />
        );
    }
    

    3.通过回调方法传值 (子组件向父组件传值)

    子组件

    // 提供参数出去,便于外部调用
    static defaultProps = {
        removeModal:{}
    }
    
    // 定义方法,便于组件触发
    popToHome(data) {
        // 向外部传值(向父组件传值)
        this.props.removeModal(data);
    }
    
    
    // 返回右边按钮
    renderRightItem() {
        return(
            <TouchableOpacity
                onPress={() => {this.popToHome(false)}}
            >
                <Text style={styles.navbarRightItemStyle}>关闭</Text>
            </TouchableOpacity>
        );
    }
    

      

    父组件

    // 接收子组件的回调
    render(){
    	return(
    		<ChartModal removeModal={(data) => this.closeModal(data)} />
    	);
    }
    
    // 根据返回值,触发事件
    closeModal(data) {
        this.setState({
            isChartModal:data
        })
    }
    

    .

  • 相关阅读:
    POJ 2411 状态压缩递,覆盖方案数
    POJ 2774 最长公共子串
    POJ 1743 不可重叠的最长重复子串
    POJ 3294 出现在至少K个字符串中的子串
    POJ 3261 出现至少K次的可重叠最长子串
    POJ 1741/1987 树的点分治
    HDU1556 Color the ball
    解决linux系统时间不对的问题
    CentOS 6.9使用Setup配置网络(解决dhcp模式插入网线不自动获取IP的问题)
    Linux网络配置(setup)
  • 原文地址:https://www.cnblogs.com/crazycode2/p/7483180.html
Copyright © 2020-2023  润新知