1.属性(Props),是用来定制组件的参数。 并且通过属性,我们可以从父组件向子组件传递数据。props在父组件之中指定,并且一经指定,在被指定的组件的生命周期中,再不能改变。
MyView.defaultProps = {text:'What the fuck Default Props!'}; //可以设置props的默认值
MyView.propTypes = {text:React.PropTypes.string}; //设置props的类型
props可认为是只读的,只可由其他组件调用该组件时从外部改变。
2.对于需要改变的数据,我们使用state,一般要在constructor中初始化state,
constructor (props){
super(props);
this.state = {
appendText:' ' //设置初始值为空白
};
}
然后设置轻按触发setState方法:
<Text onPress={()=>this.setState({appendText:' What happened'})}>
{this.props.text + this.state.appendText}</Text>
当点击文本的时候,会出现"this.props.text + What happened "
3.设置PropTypes,首先需要导入 PropTypes
import React,{Component,PropTypes} from 'react';
然后按照自己的props需求来设置
static propTypes = {
customText: PropTypes.string.isRequired,
onPress: PropTypes.func.isRequired,
}
网友评论