作家
登录

编写react组件最佳实践

作者: 来源: 2017-05-18 08:56:30 阅读 我要评论

  •             // onChange={(e) => { model.name = e.target.value }} 
  •             // ^ 不要如许写,按如下写法: 
  •             onChange={this.handleChange} 
  •             placeholder="Your Name"/>  
  • Class Based Components (基于类的组件)

    原因在于:每次父组件从新衬着时,都邑创建一个新的函数,并传给input。

    编写react组件最佳实践

    如不雅这个input是个react组件的话,这会导致无论该组件的其他属性是否变更,该组件都邑从新render。

    并且,采取将父组件的办法传入的方法也会使得代码更易读,便利调试,同时也轻易修改。

    完全代码如下:

    1. import React, { Component } from 'react' 
    2. import { observer } from 'mobx-react' 
    3. import { string, object } from 'prop-types' 
    4. // Separate local imports from dependencies 
    5. import ExpandableForm from './ExpandableForm' 
    6. import './styles/ProfileContainer.css' 
    7.  
    8. // Use decorators if needed 
    9. @observer 
    10. export default class ProfileContainer extends Component { 
    11.   state = { expanded: false } 
    12.   // Initialize state here (ES7) or in a constructor method (ES6) 
    13.   
    14.   // Declare propTypes as static properties as early as possible 
    15.   static propTypes = { 
    16.     model: object.isRequired, 
    17.     title: string 
    18.   } 
    19.  
    20.   // Default props below propTypes 
    21.   static defaultProps = { 
    22.     model: { 
    23.       id: 0 
    24.     }, 
    25.     title: 'Your Name' 
    26.   } 
    27.  
    28.   // Use fat arrow functions for methods to preserve context (this will thus be the component instance) 
    29.   handleSubmit = (e) => { 

        推荐阅读

        Java反射机制应用实践

      引言反射基本p.s: 本文须要读者对反射机制的API有必定程度的懂得,如不雅之前没有接触过的话,建议先看一下官方文档的Quick Start。在应用反射机制之前,起首我们先来看一下若何获取一个对>>>详细阅读


      本文标题:编写react组件最佳实践

      地址:http://www.17bianji.com/lsqh/35286.html

    关键词: 探索发现

    乐购科技部分新闻及文章转载自互联网,供读者交流和学习,若有涉及作者版权等问题请及时与我们联系,以便更正、删除或按规定办理。感谢所有提供资讯的网站,欢迎各类媒体与乐购科技进行文章共享合作。

    网友点评
    自媒体专栏

    评论

    热度

    精彩导读
    栏目ID=71的表不存在(操作类型=0)