reactNative学习笔记之Props属性
来源:互联网 发布:c语言程序源代码 编辑:程序博客网 时间:2024/06/06 00:37
在android当中两个页面之间传递值,可以通过bundle,那么在reactNative中,是怎么传递的呢?
没错,就是通过Props,使用方法如下
首先在我们自己的页面通过{this.props.propsName}这种方式拿到上一个页面传递过来的值,propsName表示传递的属性值名称
import React,{Component} from 'react';import {Text,View} from 'react-native';export default class PropsTest2 extends Component{render(){return (<Text style={{backgroundColor:'red',fontSize:20}}>{this.props.name}</Text>);}}然后在上一个页面怎么传值过来呢?是通过在<PropsTest2_1 name='小明'/>这种方法
import React, { Component} from 'react';import { Platform, StyleSheet, Text, View} from 'react-native';import PropsTest2_1 from './testJs/PropsTest2_1.js'export default class App extends Component{ render(){ return( <View> <PropsTest2_1 name='小明'/> </View> ); }}如果万一我们要是没传递过来,忘了传递了,我们总得有个默认值吧!如何写呢?
import React,{Component} from 'react';import {Text,View} from 'react-native';export default class PropsTest2 extends Component{static defaultProps={name:'小红-默认值'}render(){return (<Text style={{backgroundColor:'red',fontSize:20}}>{this.props.name}</Text>);}}这样就Ok了,如果说我要传递的属性比较多,怎么办?就需要用到延展操作符了
export default class App extends Component{ render(){ var params = {name:'小明',age:19,sex:'man'} return( <View> <PropsTest2_1 {...params}/> </View> ); }}这样就搞定了,还有需求的情况是,传递的参数很多,但是我只想传递一部分,只想传递几个属性,咋整?就需要用到解构赋值
export default class App extends Component{ render(){ var params = {name:'小明',age:19,sex:'man'}; var {name,age}=params; return( <View> <PropsTest2_1 {...params}/> <PropsTest2_1 name={name} age={age}/> </View> ); }}这样就搞定了,其实我们自定义组件的时候,可能会强制传递属性的时候,必须是字符串或者number类型,那么如何告诉使用我们组件的开发者呢?
import React,{Component} from 'react';import {Text,View} from 'react-native';import PropTypes from 'prop-types';export default class PropsTest2 extends Component{static defaultProps={name:'小红-默认值',age:18,// sex:'man'}static propTypes={name:PropTypes.string,sex:PropTypes.string.isRequired,}render(){return (<Text style={{backgroundColor:'red',fontSize:20}}>姓名:{this.props.name},年龄:{this.props.age},性别:{this.props.sex}</Text>);}}当你指定了某个属性是必须传递的时候,如果你还指定了默认值,那么也不会有警告的。
下边连接是视频教程
点击打开链接
阅读全文
0 0
- reactNative学习笔记之Props属性
- ReactNative学习之Props(属性)
- ReactNative:学习props的使用
- ReactNative学习十三-Props和State
- react native 学习笔记之Props
- ReactNative入门之props与state
- React 之props属性
- Vue之props属性
- React Native之Props属性
- ReactNative 学习笔记之环境搭建
- ReactNative学习笔记2(常用组件及其属性)
- React学习笔记---Props&State
- ReactNative之ListView学习总结(三)datasource 属性
- ReactNative之ListView学习总结(四)listview 属性
- ReactNative学习笔记一
- React学习(二)props属性
- 10、React系列之--props属性
- ReactNative基础---Components and Props
- Android属性动画之 一、 ValueAnimator
- nginx 负载均衡个服务器之间文件共享
- 初步了解Junit与assert
- Eclipse 常见设置和报错问题
- HAProxy系列—keepalived+haproxy实现高可用负载层
- reactNative学习笔记之Props属性
- Python 中zip()
- 算法系列(10)LeetCode520 Detect Capital
- update 语句执行十几小时问题解决
- 将解压版的Tomcat作为系统服务启动
- 二阶构造函数
- Javase—集合框架Collection
- spf13安装
- UEFI引导win10+ubuntu16.04双系统,解决“Minimal BASH-like line editing is supported”