react-native 组件之间传值

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
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

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
/**
 * 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({
 
});

 

引用 传值

1
2
3
4
5
6
7
8
9
10
11
12
13
// 引入 cell
import CommunalCell from '../main/CommunalCell';
 
// 返回每一行cell的样式
renderRow(rowData) {
    // 使用cell组件
    return(
        <CommunalCell
            name={rowData.name}
            gender={rowData.gender}
        />
    );
}

 

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

子组件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
// 提供参数出去,便于外部调用
static defaultProps = {
    removeModal:{}
}
 
// 定义方法,便于组件触发
popToHome(data) {
    // 向外部传值(向父组件传值)
    this.props.removeModal(data);
}
 
 
// 返回右边按钮
renderRightItem() {
    return(
        <TouchableOpacity
            onPress={() => {this.popToHome(false)}}
        >
            <Text style={styles.navbarRightItemStyle}>关闭</Text>
        </TouchableOpacity>
    );
}

  

父组件

1
2
3
4
5
6
7
8
9
10
11
12
13
// 接收子组件的回调
render(){
    return(
        <ChartModal removeModal={(data) => this.closeModal(data)} />
    );
}
 
// 根据返回值,触发事件
closeModal(data) {
    this.setState({
        isChartModal:data
    })
}

 

.

posted @   每天都要进步一点点  阅读(772)  评论(0编辑  收藏  举报
点击右上角即可分享
微信分享提示