美文网首页
属性(Props)和状态(State)

属性(Props)和状态(State)

作者: 大侠走一波 | 来源:发表于2017-02-16 17:37 被阅读70次

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,
    }

相关文章

网友评论

      本文标题:属性(Props)和状态(State)

      本文链接:https://www.haomeiwen.com/subject/jiuzittx.html