学习React Native必须要经历的一步就是去写一个组件,因为React Native设计思想的精髓就是组件化思想。那么如何去开始写一个基本的组件呢?我们从组件的两大组成部分Props(属性)和State(状态)来讲起。
一、Props(属性)和State(状态)
1、Props(属性)
大多数组件在创建时都可以使用各种参数来定制,用于定制的这些参数就被称为props(属性)。其实prop很好理解,它是property的缩写。props是由父组件传入的,在子控件中通过this.props来使用父组件传入的属性。props的使用方式如下所示:
import React, { Component } from 'react';
import { Text, View } from 'react-native';
//子控件
class Greeting extends Component {
render() {
return (
<Text>Hello {this.props.name}!</Text>
);
}
}
//父组件
export default class LotsOfGreetings extends Component {
render() {
return (
<View style={{alignItems: 'center'}}>
<Greeting name='Rexxar' />
<Greeting name='Jaina' />
<Greeting name='Valeera' />
</View>
);
}
}
2、State(状态)
我们使用两种数据来控制一个组件:props和state。
- props是父组件中指定,而且一经指定,在被指定的组件的生命周期中则不再改变。
- 对于需要改变的数据,我们使用state。
一般来说,我们需要在constructor中初始化state,然后在需要修改时调用setState方法。
class Blink extends Component {
constructor(props) {
super(props);
this.state = { showText: true };
// 每1000毫秒对showText状态做一次取反操作
setInterval(() => {
this.setState(previousState => {
return { showText: !previousState.showText };
});
}, 1000);
}
render() {
// 根据当前showText的值决定是否显示text内容
let display = this.state.showText ? this.props.text : ' ';
return (
<Text>{display}</Text>
);
}
}
二、自定义组件时的注意事项
1、借鉴XHTML的一些规则/规范
(1)开始结束标签配对
<组件>ooxx</组件>
(2)无内容组件标签写为自封闭形式
<组件/>
(3)自定义属性,字符串应使用双引号,其他值用{}括起来
<Person age={30} sex='male' married={true}/>
2、注意事项
(1)必须单一子节点
(2)显示和隐藏组件
(3)组件必须大写字母开头
(4)文本必须写在Text组件内
<View>React Native中文网</View>
(5)注释写法比较特殊
(6)只能嵌入表达式,不能是语句
(7)class内成员变量写法
(8)动态列表与key
- 根据数组动态生成多个组件一般使用map方法
注意,箭头函数的返回值(有{}必须写return)
- 循环生成的组件需要有唯一的key值区分
注意,key值放在循环的直接容器上
三、组件化开发举例
//第一部分:引入依赖
import React, {Component} from 'react'
import {
AppRegistry,
StyleSheet,
Text,
View,
TouchableOpacity
} from 'react-native'
//第二部分:定义组件
class App extends Component {
//组件默认自带属性
state = {
likes:0,
}
//编写onPress函数
onPress = ()=>{
const {likes}=this.state;
this.setState({
likes: likes+1i
});
}
//渲染
render() {
return(
<TouchableOpacity onPress={this.onPress}>
<Text>{this.state.likes}</Text>
</TouchableOpacity>
);
}
}
//第三部分:样式表
const styles = StyleSheet.create ({
container: {
flex:1,
justifyContent: 'center',
alignItems:'center',
backgroundColor: '#f5fcff',
},
welcome: {
fontSize:20,
textAlign: 'center'
margin:10,
},
});
//第四部分:注册组件
AppRegistry.registerComponent('App', ()=>App);
四、总结
本文是入门React Native系列文章的第三篇。对于自定义组件来说,懂得props和state的真正含义至关重要。props是在组件中不变的数据,是父组件指定的;而state是在组件中可改变的数据,每setState一次就调用一次render方法。另外作者把自己入门React Native过程中遇到的问题都总结到了一个demo里,欢迎下载后沟通交流。
demo地址(觉得ok,可以先star,会持续更新)