react static 属性props context

87 阅读1分钟

一、声明上下文属性contextTypes

如果不声明router时,this.context.router为undefine获取不到;为什么这么设计?

static contextTypes = {
        //router: PropTypes.object,
        store: PropTypes.object
    }

二、 声明属性的默认值

static defaultProps = {  
color: 'blue'  
};

三、声明属性类型

import PropTypes from 'prop-types';

static propTypes = {  
name: PropTypes.string  
};

因为一个组件内,基本包含的为context和props,所以针对两块设置了类型,但是props会涉及到不传递时,所以多了一个设置默认值。

官方文档 react.dev/reference/r…