关于React组件项目实践

开始前:

我们使用ES6、ES7语法如果你不是很清楚展示组件和容器组件的区别,建议您从阅读这篇文章开始如果您有任何的建议、疑问都清在评论里留言 基于类的组件。

现在开发React组件一般都用的是基于类的组件。下面我们就来一行一样的编写我们的组件:

import React, { Component } from 'react';import { observer } from 'mobx-react';import ExpandableForm from './ExpandableForm';import './styles/ProfileContainer.css';

登录后复制

我很喜欢css in javascript。但是,这个写样式的方法还是太新了。所以我们在每个组件里引入css文件。而且本地引入的import和全局的import会用一个空行来分割。

初始化State

import React, { Component } from 'react'import { observer } from 'mobx-react'import ExpandableForm from './ExpandableForm'import './styles/ProfileContainer.css'export default class ProfileContainer extends Component { state = { expanded: false }

登录后复制

您可以使用了老方法在constructor里初始化state。更多相关可以看这里。但是我们选择更加清晰的方法。

同时,我们确保在类前面加上了export default。(译者注:虽然这个在使用了redux的时候不一定对)。

propTypes and defaultProps

import React, { Component } from 'react'import { observer } from 'mobx-react'import { string, object } from 'prop-types'import ExpandableForm from './ExpandableForm'import './styles/ProfileContainer.css'export default class ProfileContainer extends Component { state = { expanded: false }  static propTypes = {  model: object.isRequired,  title: string }  static defaultProps = {  model: {   id: 0  },  title: 'Your Name' } // ...}

登录后复制

propTypes和defaultProps是静态属性。尽可能在组件类的的前面定义,让其他的开发人员读代码的时候可以立刻注意到。他们可以起到文档的作用。

如果你使用了React 15.3.0或者更高的版本,那么需要另外引入prop-types包,而不是使用React.PropTypes。更多内容移步这里。

你所有的组件都应该有prop types。

方法

import React, { Component } from 'react'import { observer } from 'mobx-react'import { string, object } from 'prop-types'import ExpandableForm from './ExpandableForm'import './styles/ProfileContainer.css'export default class ProfileContainer extends Component { state = { expanded: false }  static propTypes = {  model: object.isRequired,  title: string }  static defaultProps = {  model: {   id: 0  },  title: 'Your Name' } handleSubmit = (e) => {  e.preventDefault()  this.props.model.save() }  handleNameChange = (e) => {  this.props.model.changeName(e.target.value) }  handleExpand = (e) => {  e.preventDefault()  this.setState({ expanded: !this.state.expanded }) } // ...}

登录后复制

在类组件里,当你把方法传递给子组件的时候,需要确保他们被调用的时候使用的是正确的this。一般都会在传给子组件的时候这么做:this.handleSubmit.bind(this)。

使用ES6的箭头方法就简单多了。它会自动维护正确的上下文(this)。

给setState传入一个方法

在上面的例子里有这么一行:

this.setState({ expanded: !this.state.expanded });

登录后复制

setState其实是异步的!React为了提高性能,会把多次调用的setState放在一起调用。所以,调用了setState之后state不一定会立刻就发生改变。

所以,调用setState的时候,你不能依赖于当前的state值。因为i根本不知道它是值会是神马。

解决方法:给setState传入一个方法,把调用前的state值作为参数传入这个方法。看看例子:

this.setState(prevState => ({ expanded: !prevState.expanded }))

登录后复制

感谢Austin Wood的帮助。

拆解组件

import React, { Component } from 'react'import { observer } from 'mobx-react'import { string, object } from 'prop-types'import ExpandableForm from './ExpandableForm'import './styles/ProfileContainer.css'export default class ProfileContainer extends Component { state = { expanded: false }  static propTypes = {  model: object.isRequired,  title: string }  static defaultProps = {  model: {   id: 0  },  title: 'Your Name' } handleSubmit = (e) => {  e.preventDefault()  this.props.model.save() }  handleNameChange = (e) => {  this.props.model.changeName(e.target.value) }  handleExpand = (e) => {  e.preventDefault()  this.setState(prevState => ({ expanded: !prevState.expanded })) }  render() {  const {   model,   title  } = this.props  return (        

     

{title}

              ) }}

登录后复制

有多行的props的,每一个prop都应该单独占一行。就如上例一样。要达到这个目标最好的方法是使用一套工具:Prettier。

装饰器(Decorator)

@observerexport default class ProfileContainer extends Component {

登录后复制

如果你了解某些库,比如mobx,你就可以使用上例的方式来修饰类组件。装饰器就是把类组件作为一个参数传入了一个方法。

装饰器可以编写更灵活、更有可读性的组件。如果你不想用装饰器,你可以这样:

class ProfileContainer extends Component { // Component code}export default observer(ProfileContainer)

登录后复制

闭包

尽量避免在子组件中传入闭包,如:

 { model.name = e.target.value }} // ^ Not this. Use the below: onChange={this.handleChange} placeholder="Your Name"/>

登录后复制

注意:如果input是一个React组件的话,这样自动触发它的重绘,不管其他的props是否发生了改变。

一致性检验是React最消耗资源的部分。不要把额外的工作加到这里。处理上例中的问题最好的方法是传入一个类方法,这样还会更加易读,更容易调试。如:

import React, { Component } from 'react'import { observer } from 'mobx-react'import { string, object } from 'prop-types'// Separate local imports from dependenciesimport ExpandableForm from './ExpandableForm'import './styles/ProfileContainer.css'// Use decorators if needed@observerexport default class ProfileContainer extends Component { state = { expanded: false } // Initialize state here (ES7) or in a constructor method (ES6)  // Declare propTypes as static properties as early as possible static propTypes = {  model: object.isRequired,  title: string } // Default props below propTypes static defaultProps = {  model: {   id: 0  },  title: 'Your Name' } // Use fat arrow functions for methods to preserve context (this will thus be the component instance) handleSubmit = (e) => {  e.preventDefault()  this.props.model.save() }  handleNameChange = (e) => {  this.props.model.name = e.target.value }  handleExpand = (e) => {  e.preventDefault()  this.setState(prevState => ({ expanded: !prevState.expanded })) }  render() {  // Destructure props for readability  const {   model,   title  } = this.props  return (        // Newline props if there are more than two    

     

{title}

      { model.name = e.target.value }}      // Avoid creating new closures in the render method- use methods like below      onChange={this.handleNameChange}      placeholder="Your Name"/>         ) }}

登录后复制

方法组件

这类组件没有state没有props,也没有方法。它们是纯组件,包含了最少的引起变化的内容。经常使用它们。

propTypes

import React from 'react'import { observer } from 'mobx-react'import { func, bool } from 'prop-types'import './styles/Form.css'ExpandableForm.propTypes = { onSubmit: func.isRequired, expanded: bool}// Component declaration

登录后复制

我们在组件的声明之前就定义了propTypes。

分解Props和defaultProps

import React from 'react'import { observer } from 'mobx-react'import { func, bool } from 'prop-types'import './styles/Form.css'ExpandableForm.propTypes = { onSubmit: func.isRequired, expanded: bool, onExpand: func.isRequired}function ExpandableForm(props) { const formStyle = props.expanded ? {height: 'auto'} : {height: 0} return (  

登录后复制 )}

我们的组件是一个方法。它的参数就是props。我们可以这样扩展这个组件:

import React from 'react'import { observer } from 'mobx-react'import { func, bool } from 'prop-types'import './styles/Form.css'ExpandableForm.propTypes = { onSubmit: func.isRequired, expanded: bool, onExpand: func.isRequired}function ExpandableForm({ onExpand, expanded = false, children, onSubmit }) { const formStyle = expanded ? {height: 'auto'} : {height: 0} return (  

登录后复制登录后复制 )}

现在我们也可以使用默认参数来扮演默认props的角色,这样有很好的可读性。如果expanded没有定义,那么我们就把它设置为false。

但是,尽量避免使用如下的例子:

const ExpandableForm = ({ onExpand, expanded, children }) => {

登录后复制

看起来很现代,但是这个方法是未命名的。

如果你的Babel配置正确,未命名的方法并不会是什么大问题。但是,如果Babel有问题的话,那么这个组件里的任何错误都显示为发生在 里的,这调试起来就非常麻烦了。

匿名方法也会引起Jest其他的问题。由于会引起各种难以理解的问题,而且也没有什么实际的好处。我们推荐使用function,少使用const。

装饰方法组件

由于方法组件没法使用装饰器,只能把它作为参数传入别的方法里。

import React from 'react'import { observer } from 'mobx-react'import { func, bool } from 'prop-types'import './styles/Form.css'ExpandableForm.propTypes = { onSubmit: func.isRequired, expanded: bool, onExpand: func.isRequired}function ExpandableForm({ onExpand, expanded = false, children, onSubmit }) { const formStyle = expanded ? {height: 'auto'} : {height: 0} return (  

登录后复制登录后复制 )}export default observer(ExpandableForm)

只能这样处理:export default observer(ExpandableForm)。

这就是组件的全部代码:

import React from 'react'import { observer } from 'mobx-react'import { func, bool } from 'prop-types'// Separate local imports from dependenciesimport './styles/Form.css'// Declare propTypes here, before the component (taking advantage of JS function hoisting)// You want these to be as visible as possibleExpandableForm.propTypes = { onSubmit: func.isRequired, expanded: bool, onExpand: func.isRequired}// Destructure props like so, and use default arguments as a way of setting defaultPropsfunction ExpandableForm({ onExpand, expanded = false, children, onSubmit }) { const formStyle = expanded ? { height: 'auto' } : { height: 0 } return (  

登录后复制 )}// Wrap the component instead of decorating itexport default observer(ExpandableForm)

条件判断

某些情况下,你会做很多的条件判断:

 {props.downloadMode && currentImage && !currentImage.video && currentImage.blogText ? !currentImage.submitted && !currentImage.posted ? 

Please contact us for content usage

  : currentImage && currentImage.selected   ?    : currentImage && currentImage.submitted    ?     : currentImage && currentImage.posted     ?      :  }

登录后复制

这么多层的条件判断可不是什么好现象。

有第三方库JSX-Control Statements可以解决这个问题。但是与其增加一个依赖,还不如这样来解决:

 {  (() => {   if(downloadMode && !videoSrc) {    if(isApproved && isPosted) {     return 

Right click image and select "Save Image As.." to download

    } else {     return 

Please contact us for content usage

    }   }   // ...  })() }

登录后复制

使用大括号包起来的IIFE,然后把你的if表达式都放进去。返回你要返回的组件。

相关推荐:

React组件性能优化方法解答

React组件生命周期实例分析

构建React组件最全方法

以上就是关于React组件项目实践的详细内容,更多请关注【创想鸟】其它相关文章!

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至253000106@qq.com举报,一经查实,本站将立刻删除。

发布者:PHP中文网,转转请注明出处:https://www.chuangxiangniao.com/p/2785178.html

(0)
上一篇 2025年3月8日 17:22:10
下一篇 2025年3月8日 17:22:17

AD推荐 黄金广告位招租... 更多推荐

相关推荐

  • React组件的性能优化方法

    1. 单个react组件的性能优化 React利用Virtual DOM来提升渲染性能,虽然每一次页面更新都是最组件的从新渲染,但是并不是将之前的渲染内容全部抛弃重来,借助Virtual DOM,React能够计算出对DOM树的最少修改,这…

    编程技术 2025年3月8日
    200
  • React Native如何使用fetch实现图片上传

    本文介绍了react native使用fetch实现图片上传的示例代码,分享给大家,具体如下:普通网络请求参数是json对象 图片上传的请求参数使用的是formdata对象 使用fetch上传图片代码封装如下: let common_url…

    编程技术 2025年3月8日
    200
  • 详解react关于事件绑定this的四种方式_javascript技巧

    在react组件中,每个方法的上下文都会指向该组件的实例,即自动绑定this为当前组件,而且react还会对这种引用进行缓存,以达到cpu和内存的最大化。在使用了es6 class或者纯函数时,这种自动绑定就不复存在了,我们需要手动实现th…

    编程技术 2025年3月8日
    200
  • 细说什么是js中的事件冒泡和事件捕获以及事件委托

    谈起javascript的 事件,事件冒泡、事件捕获、事件委托这三个话题,无论是面试还是在平时的javascript的开发中,都很难避免,不太熟悉javascript中的这些事件的同学,我们一起来看看本篇文章吧! 事件流   JavaScr…

    2025年3月8日 编程技术
    200
  • React中给div设置html

    这次给大家带来react中给div设置html,react中给div设置html的注意事项有哪些,下面就是实战案例,一起来看一下。 在使用React开发过程中,发现$(“#dataDetail”).html(&#82…

    2025年3月8日
    200
  • React怎样给button添加事件

    这次给大家带来react怎样给button添加事件,react给button添加事件的注意事项有哪些,下面就是实战案例,一起来看一下。 在使用React过程中,为自定义Table组件中的button添加OnClick事件,发现使用 评估报表…

    编程技术 2025年3月8日
    200
  • javascript实现线程以及事件循环详解

     本篇文章讲述了javascript实现线程以及事件循环,大家对javascript实现线程以及事件循环不了解的话或者对javascript实现线程以及事件循环感兴趣的话那么我们就一起来看看本篇文章吧, 好了废话少说进入正题吧 1.为什么说…

    2025年3月8日
    200
  • js中的事件委托

    本文主要和大家分享js中的事件委托实例详解,我们主要和大家分享两个内容1.事件委托的原理以及优缺点 2. 手写原生js实现事件代理,并要求兼容浏览器。 q:事件的委托(代理 delegated events)的原理以及优缺点 A:委托(代理…

    编程技术 2025年3月8日
    200
  • 怎样防止相同的事件重复的触发

    这次给大家带来怎样防止相同的事件重复的触发,防止相同的事件重复触发的注意事项有哪些,下面就是实战案例,一起来看一下。 重复触发就是防止用户重复点击提交数据了,我们一般都是点击之后没反应会再次点击了,这个不但要从用户体验上来做好,还在要js或…

    编程技术 2025年3月8日
    200
  • JavaScript的事件管理

    这次给大家带来javascript的事件管理,使用javascript的事件管理的注意事项有哪些,下面就是实战案例,一起来看一下。 在设计JavaScript xxsdk的时候考虑到能让调用者参与到工作流程中来,开始用了回调函数。如下: t…

    2025年3月8日
    200

发表回复

登录后才能评论