[关闭]
@brizer 2016-02-12T14:05:26.000000Z 字数 1572 阅读 1059

React Up&Running第二章The life of a component


前言

本章主要是讲解一些有关组件数据传递和生命周期还有提高复用性的基础。
之前的笔记中也有相应的提到过,这里再次巩固了一遍。


propTypes

propTypes是一共列表,这个列表中定义了组件可以接受的属性以及它们的类型。前面我也写过
使用优势:1.使用这个组件的时候可以直接在propTypes找到对应属性的类型,而不用再去render方法中查找;2.React会自动根据propTypes在运行的时候进行验证传入的属性。

至于这里说的第一点优势,可以举一个例子,就是我们在多层子级中调用某一父类的属性时,propTypes配合context的使用:

  1. var MyContainer = React.createClass({
  2. getInitialState: function(){
  3. return {
  4. curItem: 'item1'
  5. }
  6. },
  7. //验证数据类型,这个必须要
  8. childContextTypes: {
  9. curItem: React.PropTypes.any,
  10. changeItem: React.PropTypes.any
  11. },
  12. getChildContext: function(){
  13. return {
  14. curItem: this.state.curItem,
  15. changeItem: this.changeItem
  16. }
  17. },
  18. changeItem: function(item){
  19. this.setState({
  20. curItem: item
  21. });
  22. },
  23. render: function(){
  24. return (
  25. <div>
  26. <CurItemWrapper />
  27. <ListWrapper changeItem={this.changeItem}/>
  28. </div>
  29. )
  30. }
  31. });
  32. var CurItemWrapper = React.createClass({
  33. render: function(){
  34. return (
  35. <div>
  36. <CurItemPanel />
  37. </div>
  38. )
  39. }
  40. });
  41. //通过this.context.***直接调用祖先级别的属性
  42. var CurItemPanel = React.createClass({
  43. contextTypes: {
  44. curItem: React.PropTypes.any
  45. },
  46. render: function(){
  47. return (
  48. <p>
  49. The curItem is: {this.context.curItem}
  50. </p>
  51. )
  52. }
  53. });
  54. var ListWrapper = React.createClass({
  55. render: function(){
  56. return (
  57. <div>
  58. <List />
  59. </div>
  60. )
  61. }
  62. });
  63. var List = React.createClass({
  64. contextTypes: {
  65. changeItem: React.PropTypes.any
  66. },
  67. //this.context.changeItem祖先级方法
  68. onClickItem: function(item){
  69. this.context.changeItem(item);
  70. },
  71. render: function(){
  72. return (
  73. <ul>
  74. <li onClick={this.onClickItem.bind(this, 'item1')}>I am item1, click me!</li>
  75. <li onClick={this.onClickItem.bind(this, 'item2')}>I am item2, click me!</li>
  76. </ul>
  77. )
  78. }
  79. });

完整的propTypes列表如下:


state和props

这个相对基础,stateprops都比较容易掌握, 我们可以把props理解为只读的属性,而state为需要交互的属性。


生命周期

生命周期我在前面也有说过,在不同的阶段会调用不同的方法,所以我们需要自己安排合适的位置。

添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注