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
})
}
.

浙公网安备 33010602011771号