React Native state props(ES6 定义)

版本显示:React-Native -v

react-native-cli:0.2.0
react-native:0.22.2

关于props state 问题1:

ES6语言风格下,使用如下方式定义propsstate提示如下:


getInitialState(){}

getDefaultProps() {}

Waring:getDefaultProps was defined on xxx,a plain javascript class. This is only supported for classes created using React.createClass.Use a static property to define defaultProps instead.

也就是说,在ES6 的风格下以上是不被推荐的,而是换成如下方式:

  • 定义props:
static defaultProps={
  name:'xxxx',
  age:10
}
  • 定义 state:
    则在是constructor构造方法中定义相关state
constructor(props) {
    super(props);
    this.state = {name:'xxx'};

  }

完整如下 :

ES6 Classes: The API is similar to React.createClass with the exception of getInitialState. Instead of providing a separate getInitialState method, you set up your own state property in the constructor.
Another difference is that propTypes and defaultProps are defined as properties on the constructor instead of in the class body.

 static defaultProps={
    age:12,
    name:'xxx'
}
constructor(props) {
    super(props);
    this.state = {address:'深圳南山区'};

  }

关于state props 的含义与区别可以点

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容