ReactNative組件間的通信

父組件向子組件通信

  • 父組件向子組件傳值
  • 通過props傳遞 在父組件中name='我是父組件向子組件傳遞的參數(shù)'
  • 在子組件中通過this.props.name獲取
  • 父組件向子組件傳遞方法
  • 與傳遞參數(shù)方法相同,通過props方法這樣傳遞test={this.onParentClick1}
  • 在子組件中觸發(fā)這個方法this.props.test();

子組件向父組件通信

  • 子組件向父組件傳值
  • 在子組件state中定義一個參數(shù)this.state = {name : '我是子組件向父組件傳遞的參數(shù)' };
  • 在父組件中給子組件綁定ref,如 <Childern ref='childern' />
  • 在父組件中獲取子組件的state,如this.refs.childern.state.name
  • 子組件向父組件傳遞方法
  • 同樣通過ref來獲得,前兩部與傳參方法相同。
  • 獲取方法的方式也同樣this.refs.childern.onChildenCilck2();

非父子組件之間的傳值

  • 組件之間無關(guān)聯(lián)的形式與子組件向父組件傳值的方式相同
  • 通過ref給組件標(biāo)記一個名字,同樣通過this.refs.***.state/function方法相互調(diào)用。

demo示例

父子組件通信demo
  • 點擊父組件按鈕打印子組件的state和方法

    打印日志1

  • 點擊子組件按鈕打印父組件的傳遞的參數(shù)和方法


    打印日志2
/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 * @flow
 */

import React, { Component } from 'react';
import {
  AppRegistry,
  StyleSheet,
  Text,
  View,
  TouchableOpacity
} from 'react-native';

export default class JSXDemo extends Component {
  render() {
    return (
      <View style={styles.bg}>
        <Parents />
      </View>

    );
  }
}


class Parents extends Component{
  render(){

    return(
      <View style={styles.parents}>
        <Childern ref='childern' name='我是父組件向子組件傳遞的參數(shù)' test={this.onParentClick1} />
        <Text >
          我是父組件
        </Text>
        <TouchableOpacity onPress={this.onParentClick2}>
          <Text style={styles.btn}>
            我是父組件按鈕
          </Text>
        </TouchableOpacity>


      </View>
    )
  }
  onParentClick1 = ()=>{

    console.log('我是從父組件傳遞到子組件的方法');

  }
  onParentClick2 = ()=>{

    console.log(this.refs.childern.state.name);
    this.refs.childern.onChildenCilck2();

  }
}

class Childern extends Component {


  constructor(props) {
    super(props);
    this.state = {
      name : '我是子組件向父組件傳遞的參數(shù)'
    };
  }
  onChildenCilck1 = () =>{
    console.log(this.props.name);
    this.props.test();
  }

  onChildenCilck2 = () =>{

    console.log('我是子組件向父組件傳遞的方法');
  }

  render(){
    return(
      <View style={styles.childern}>
        <Text> 我是子組件 </Text>
          <TouchableOpacity onPress={this.onChildenCilck1}>
            <Text style={styles.btn}>
              我是子組件按鈕
            </Text>
          </TouchableOpacity>
      </View>
    )
  }
}

const styles = StyleSheet.create({
  bg:{
    flex:1,
    justifyContent:'center',
    alignItems:'center'
  },
  parents: {
    width:300,
    height:300,
    backgroundColor:'red',
    justifyContent:'center',
    alignItems:'center'
  },
  childern: {
    width:100,
    height:100,
    marginTop:10,
    backgroundColor:'green',
    justifyContent:'center',
    alignItems:'center'

  },
  btn:{

    backgroundColor:'yellow',

  }

});

AppRegistry.registerComponent('JSXDemo', () => JSXDemo);

Navigator傳值

  • push傳值
  • 首先在路由上配置{...route.params}
render() {
    let rootViewName = 'FirstView';
    let rootComponent = FirstView;

    return (
      <Navigator
        initialRoute = {{ name: rootViewName, component: rootComponent }}
        configureScene = {(route) => {
          return Navigator.SceneConfigs.HorizontalSwipeJump ;
        }}
        renderScene = {(route, navigator) => {
          let Component = route.component;
          return <Component {...route.params} navigator = {navigator} />
        }} />
    );
  }
  • 然后在push的時候傳params屬性,下面的id: Id,就是我們要傳遞下去的參數(shù)
push = (Id) =>{
    var _this = this;
    const navigator = this.props.navigator;
    if (navigator) {
      navigator.push({
        name: 'SecondView',
        component: SecondView,
        params: {
          id: Id,
          getUser: function(user) {
            _this.setState({
              user: user
            })
          }
        }
      });
    }
  }
  • 最后在二級界面通過props屬性來接收,this.props.id就是上個界面?zhèn)鬟f過來的參數(shù)
componentDidMount() {
      this.setState({
        Id : this.props.id
      });
  }
  • pop回調(diào)
  • 首先在一級界面將一個方法通過params向二級界面?zhèn)鬟f。下面的getUser: function(user) 方法就是我們傳遞下去的方法
push = (Id) =>{
    var _this = this;
    const navigator = this.props.navigator;
    if (navigator) {
      navigator.push({
        name: 'SecondView',
        component: SecondView,
        params: {
          id: Id,
          getUser: function(user) {
            _this.setState({
              user: user
            })
          }
        }
      });
    }
  }
  • 在二級界面pop回調(diào)的時候,通過props觸發(fā)這個方法。這樣就實現(xiàn)了回調(diào)
pop = () =>{
    if (this.props.navigator) {
      this.props.navigator.pop();
      let user = USER_MODELS[this.state.Id];
      this.props.getUser(user);
    }
  }
  • 上面的user就是回傳的參數(shù),在回調(diào)方法getUser中進行處理

  • 代碼展示

  • index.ios.js路由配置

import React, { Component } from 'react';
import {
  AppRegistry,
  StyleSheet,
  Text,
  View,
  Navigator
} from 'react-native';
import FirstView from './FirstView'
export default class ZZHNavigator extends Component {
  render() {
    let rootViewName = 'FirstView';
    let rootComponent = FirstView;
    return (
      <Navigator
        initialRoute = {{ name: rootViewName, component: rootComponent }}
        configureScene = {(route) => {
          return Navigator.SceneConfigs.HorizontalSwipeJump ;
        }}
        renderScene = {(route, navigator) => {
          let Component = route.component;
          return <Component {...route.params} navigator = {navigator} />
        }} />
    );
  }
}
const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#F5FCFF',
  },
  welcome: {
    fontSize: 20,
    textAlign: 'center',
    margin: 10,
  },
  instructions: {
    textAlign: 'center',
    color: '#333333',
    marginBottom: 5,
  },
});
AppRegistry.registerComponent('ZZHNavigator', () => ZZHNavigator);
  • FirstView一級界面
import React, { Component } from 'react';
import {
  StyleSheet,
  Text,
  View
} from 'react-native';
import SecondView from './SecondView';
class FirstView extends Component {
  constructor(props) {
    super(props);
    this.state = {
      user : null
    };
  }
  push = (Id) =>{
    var _this = this;
    const navigator = this.props.navigator;
    if (navigator) {
      navigator.push({
        name: 'SecondView',
        component: SecondView,
        params: {
          id: Id,
          getUser: function(user) {
            _this.setState({
              user: user
            })
          }
        }
      });
    }
  }
  render() {
    return (
      <View style={styles.flex}>
        <Text style = {styles.btn} onPress = {() => this.push(0)}>
          查詢ID為0的學(xué)生信息
        </Text>
        <Text style = {styles.btn} onPress = {() => this.push(1)}>
          查詢ID為1的學(xué)生信息
        </Text>
        <Text style = {styles.btn} >
          {
            this.state.user? JSON.stringify(this.state.user) : ''
          }
        </Text>
      </View>
    );
  }
}
const styles = StyleSheet.create({
  flex:{
    flex:1,
    justifyContent:'center',
    alignItems:'center',
  },
  btn:{
    marginTop:10,
    padding:5,
    backgroundColor:'red',
    color:'white',
  }
});
export default FirstView;
  • SecondView二級界面
import React, { Component } from 'react';
import {
  StyleSheet,
  Text,
  View
} from 'react-native';
const USER_MODELS = {
  0: { 姓名: '小明', 性別: '男' },
  1: { 姓名: '韓梅梅', 性別: '女' }
};
class SecondView extends Component {
  constructor(props) {
    super(props);
    this.state = {
      Id : null
    };
  }
  componentDidMount() {
      this.setState({
        Id : this.props.id
      });
  }
  pop = () =>{
    if (this.props.navigator) {
      this.props.navigator.pop();
      let user = USER_MODELS[this.state.Id];
      this.props.getUser(user);
    }
  }
  render() {
    return (
      <View style={styles.flex}>
        <Text style = {styles.btn}>
          我是學(xué)生{this.state.Id}信息
        </Text>
        <Text style = {styles.btn}>
          {
            JSON.stringify(USER_MODELS[this.state.Id])
          }
        </Text>
        <Text style = {styles.btn} onPress = {() => this.pop()}>
          點我返回上一頁
        </Text>
      </View>
    );
  }
}
const styles = StyleSheet.create({
  flex:{
    flex:1,
    justifyContent:'center',
    alignItems:'center',
  },
  btn:{
    marginTop:10,
    padding:5,
    backgroundColor:'red',
    color:'white',
  }
});
export default SecondView;
  • Demo展示
  • 一級界面有兩個學(xué)生按鈕,點擊跳向二級界面,分別傳遞不同的id
    FirstView.jpeg
  • 二級界面通過傳過來學(xué)生id,在字典中得到相應(yīng)的學(xué)生數(shù)據(jù)。
    SecondView.jpeg
  • 點擊按鈕返回一級界面,講二級界面得到的學(xué)生對象user回傳給一級界面,并且通過回調(diào)方法,將數(shù)據(jù)渲染在界面上。
    回調(diào).jpeg
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • View 個人感覺View就類似于html中的div標(biāo)簽,支持flexbox布局。 一個簡單的練習(xí),類似攜程的格子...
    45b645c5912e閱讀 1,311評論 0 0
  • 一.簡介 使用導(dǎo)航器可以讓你在應(yīng)用的不同場景(頁面)間進行切換。導(dǎo)航器通過路由對象來分辨不同的場景。利用rende...
    飛奔的小馬閱讀 890評論 0 0
  • 公司打算用react-native開發(fā)APP,初始RN遇到了很多坑,搭建了一個小的項目框架,結(jié)合redux根據(jù)公司...
    45b645c5912e閱讀 813評論 0 5
  • Spring Cloud為開發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見模式的工具(例如配置管理,服務(wù)發(fā)現(xiàn),斷路器,智...
    卡卡羅2017閱讀 136,554評論 19 139
  • 一路晃晃蕩蕩,來到江南水鄉(xiāng),擁擠的人潮自然是不用說,但是三天的小長假阻擋不住全國老的少的男的女的們漂洋過海來看你的...
    大仙女兒閱讀 379評論 0 2

友情鏈接更多精彩內(nèi)容