### props和state
-------
React Native中的props和state和React中的是一样的
props属性| state状态 |
| --- | --- |
| 不可变 | 可变 |
| 在父组件指定,传递过来 | 私有的 |
| | 每次改变会重新render |
#### 1. props:组件的属性
一般用于嵌套的内外组件中,负责传递信息(父组件 → 子组件)。
不要试图去修改props值

```
//ES6
class App extends React.Component {
//默认属性
static defaultProps = {
name: "sherry",
age: 20,
}; // 注意这里有分号
//属性类型检查
static propTypes = {
name: React.PropTypes.string.isRequired,
age: React.PropTypes.number.isRequired
}; // 注意这里有分号
render() {
return (
<View>
<YourComponent name={this.props.name} age={this.props.age}/> //将属性传递给子组件
</View>
);
} // 注意这里既没有分号也没有逗号
}
class YourComponent extends React.Component {
render(){
// 接收父组件传递过来的props属性
return (
<View>
<Text>name: {this.props.name},age: {this.props.age}</Text>
</View>
)
}
}
```
```
render() {
//先定义常量赋值,更清晰
const {
name,
age
} = this.props;
return (
<View>
<YourComponent name={name} age={age}/> //将属性传递给子组件
</View>
);
}
```
如果要将所有props传递给子组件,可以使用延展操作符{...props}。
```
<YourComponent {...props}/>
```
经常我们只需要部分的属性,这时可以通过解构更方便。
```
const {
name,
age
} = this.props;
```
**this.props.children**
代表组件的所有子节点。在组件内容不确定的时候,在创建模板时才能确定时,需要从父组件获取内容。特别适合自己定义好的组件给别人用时,里面的内容需要用户自定义的。
~~~
class ListComponent extends Component {
render(){
return (
<View>
{this.props.children}
</View>
)
}
}
class app extends Component {
render(){
return (
<ListComponent>
<Text>1. Hello React</Text>
<Text>2. Hello React Native</Text>
</ListComponent>
)
}
}
~~~
#### 2.state:组件的状态
定义state的方式
```
class APP extends React.Component {
state = {
name: this.props.name, //初始化state
}
}
```
```
//推荐这种方式
class App extends React.Component {
constructor(props){
super(props);
this.state = {
name: this.props.name,
};
}
}
```
通过setState来改变state,从而重新渲染组件,到达交互效果
```
this.setState({
name: "xiaoming" //只需要写改变的state
})
```
一般用户的事件交互都是通过改变state来实现的。
但是在一些变化较快的动画场景的不适用,比如随着手指的上滑图片不断变小,可以直接使用`setNativeProps`方法。
```
this.content.setNativeProps(this._contentStyle);
<View ref={ref => {this.content = ref;}}></View>
```
