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 }) } |
.
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步