react native navigation 参数传递调用

来源:互联网 发布:2016淘宝最大的店铺 编辑:程序博客网 时间:2024/06/05 14:21

代码分析如下

参数传递分析
CategoryContainer.js中设置参数

onPress={() => {  navigation.state.params.handleCheck();}}Category.js中if (params === undefined || !params.isFirst) {  this.props.navigation.setParams({ handleCheck: this.onActionSelected });}

1、props属性

通过父组件 为Child,引用的组件为子组件,如 ChildName和ChildTel
子组件中 有属性name 和 tel,那么我们就可以在父组件中
进行 key={value} 的形式设置

class Child extends Component{      render(){        return(            <View>                <ChildName name={this.props.ChildName}/>                <ChildTel tel={this.props.ChildTel}/>           </View>         );     }  class ChildName extends Component{     render(){        return(            <Text>{this.props.name}</Text>         );     }  }  class ChildTel extends Component{    render(){         return(            <Text>{this.props.tel}</Text>        );      }  }  }  

这里的name和tel是子组件的属性,然后我们用父组件的属性传递给子组件,那么父组件的属性就是ChildName和ChildTel。也就是说我们设置父组件的属性时那么他的子组件props属性也会被赋值。

return (             <Child                 ChildName="小明"                ChildTel="18912345678"/>      );  

2、另一种妙用

<子组件 {...this.props}></子组件>

如下

<Text>{this.props.name}</Text>  

这是相当于 将 父组件拥有的属性传递给子组件

如果父组件有,点击响应,那么子组件也会有
有个例外

This.props.children,这个返回的是组件的所有子节点
是一个数组对象

经典妙用
1.CategoryContainer.js中初始化,中为导航栏右上角点击动作

声明了函数

 navigation.state.params.handleCheck();

声明时候用的是

onPress={() => {  navigation.state.params.handleCheck();}}tabBarIcon: ({ tintColor }) =>  <Icon name="md-pricetags" size={25} color={tintColor} />,headerRight: navigation.state.params !== undefined &&  navigation.state.params.isFirst  ? null  : <Icon.Button      name="md-checkmark"      backgroundColor="transparent"      underlayColor="transparent"      activeOpacity={0.8}      onPress={() => {        navigation.state.params.handleCheck();      }}    />

2、通过

render() {  return <Category {...this.props} />;}

将CategoryContainer.js父控件中的 所有属性,当然包括
This.props.navigation 对象

但是对于 navigation对象中的 params下的属性

只能够通过调用 navigation下的 setParams({key:value})的形式进行赋值

3、在Category.js中
首先 获取 params,,,然后再进行设置

componentDidMount() {  const { params } = this.props.navigation.state;  if (params === undefined || !params.isFirst) {     this.props.navigation.setParams({ handleCheck: this.onActionSelected });  }}

复习一下

Navigation中的变量

(1)This.navigation. goBack()返回上一页

(2)This.navigation state 通过state对象可以获取其内部的
routeName 路由名称, key 界面表示, 和 params
其中 params中可以进行 变量声明,或者变量定义

(3)This.navigation setParams方法 可以对 params中key进行设置value
(4)dispatch 方法,,主要是dispatch一些action以后详述

函数定义方法
onPress = {this.函数名.bind(this)}
onPress={() =>this.函数名()}
或者带参数的 onPress={(参数1,参数2) => this.函数名(参数1,参数2)}
前面的(参数1,参数2)类似函数转接

第三种可以 保存函数引用

 constructor(props){        super(props);        this._onAppPaused = this.onAppPaused.bind(this);    }  onPress={this._onAppPaused}_onAppPaused  为指向函数的引用onAppPaused为函数

父子组件同一界面,父声明,传递参数…this.props,子组件定义建立指向关系。

参考
http://blog.csdn.net/superbiglw/article/details/54344032
以及饿了么开源代码分析

原创粉丝点击