React Native从零开始(三)Props(属性)和State(状态)
一、Props(属性)
props是组件自身的属性,一般用于嵌套的内外层组件中,负责传递信息(通常由父层组件向子层组件传递)
注意:props对象中的属性与组件的属性一一对应,不要直接去修改props中属性的值
因为官网上已经有了他的基本使用方法,但是可能还是不能够很好的理解Props属性,那么可以看一看下面的使用示例。
1、父组件向子组件参数的传递
首先创建两个自定义的组件ChildName和ChildTel
class ChildName extends Component{
render(){
return(
<Text>{this.props.name}</Text>
);
}
}
class ChildTel extends Component{
render(){
return(
<Text>{this.props.tel}</Text>
);
}
}
这里的{this.props.tel},{this.props.name},是这两个子控件的属性。然后我们创建一个父组件包含这两个子组件,然后利用这个父组件像子组件传递数据
class Child extends Component{
render(){
return(
<View>
<ChildName name={this.props.ChildName}/>
<ChildTel tel={this.props.ChildTel}/>
</View>
);
}
}
这里的name和tel是子组件的属性,然后我们用父组件的属性传递给子组件,那么父组件的属性就是ChildName和ChildTel。也就是说我们设置父组件的属性时那么他的子组件props属性也会被赋值。
return (
<Child
ChildName="小明"
ChildTel="18912345678"/>
);
最后的效果如下:
2、...this.props的使用
是props提供的语法糖,可以将父组件的全部属性复制给子组件,也就是说我们不需要为子组件设置属性,利用这个将会把父组件的属性赋予给子组件
PersonClick (){
alert("点击效果");
}
constructor(props) {
super(props);
}
render() {
return (
<Person
name="小明"
tel="18912345678"
onPress={this.PersonClick}/>
);
}
这个时候我们看到父组件有一个函数是alert输出个字符串,如果我们不使用...this.props那么点击控件,不会有点击效果
render(){
return(
<Text >{this.props.name}</Text>
);
}
那么我们加上这句话再来点击可以有点击效果
render(){
return(
<Text {...this.props}>{this.props.name}</Text>
);
}
3.this.props.childer
childer是一个例外不是跟组件的属性对应的。表示组件的所有子节点。
因为列表或者控件中的子控件数目,不确定,所以我们需要遍历children,逐项进行设置,使用React.Childer.map方法
返回值:数组对象。
子控件
render(){
return(
<View>
{
React.Children.map(this.props.children,function (child) {
return (
<View>{child}</View>
);
})
}
</View>
);
}
父控件
render() {
return (
<Person>
<Text>小明</Text>
<Text>18812345678</Text>
<Text>12岁</Text>
</Person>
);
}
4、设置组件属性的默认值
就是组件在不设置属性的值的时候为其设置一个默认的值ES6语法下的
render() {
return (
<Person/>
);
}
子控件
static defaultProps={
name:'xxxx',
};
render(){
return(
<Text>{this.props.name}</Text>
);
}
这个时候的显示效果是
二、State(状态)
我们使用两种数据来控制一个组件:props和state。props是在父组件中指定,而且一经指定,在被指定的组件的生命周期中则不再改变。 对于需要改变的数据,我们需要使用state。
一般来说,你需要在constructor中初始化state(译注:这是ES6的写法,早期的很多ES5的例子使用的是getInitialState方法来初始化state,这一做法会逐渐被淘汰),然后在需要修改时调用setState方法。
官网的例子写的很容易理解
import React, { Component } from 'react';
import { AppRegistry, Text, View } from 'react-native';
class Blink extends Component {
constructor(props) {
super(props);
this.state = { showText: true };
// 每1000毫秒对showText状态做一次取反操作
setInterval(() => {
this.setState({ showText: !this.state.showText });
}, 1000);
}
render() {
// 根据当前showText的值决定是否显示text内容
let display = this.state.showText ? this.props.text : ' ';
return (
<Text>{display}</Text>
);
}
}
class BlinkApp extends Component {
render() {
return (
<View>
<Blink text='I love to blink' />
<Blink text='Yes blinking is so great' />
<Blink text='Why did they ever take this out of HTML' />
<Blink text='Look at me look at me look at me' />
</View>
);
}
}
AppRegistry.registerComponent('BlinkApp', () => BlinkApp);
效果如下