目录
开始前:
方法
首页 web前端 H5教程 React组件的使用详解

React组件的使用详解

Mar 27, 2018 pm 03:49 PM
react 组件 详解

这次给大家带来React组件的使用详解,使用React组件的注意事项有哪些,下面就是实战案例,一起来看一下。

当我刚开始写React的时候,我看过很多写组件的方法。一百篇教程就有一百种写法。虽然React本身已经成熟了,但是如何使用它似乎还没有一个“正确”的方法。所以我(作者)把我们团队这些年来总结的使用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'
 }
 // ...
}
登录后复制

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

如果你使用了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)

@observer
export default class ProfileContainer extends Component {
登录后复制

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

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

class ProfileContainer extends Component {
 // Component code
}
export default observer(ProfileContainer)
登录后复制


闭包

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

<input
 type="text"
 value={model.name}
 // onChange={(e) => { 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 dependencies
import ExpandableForm from './ExpandableForm'
import './styles/ProfileContainer.css'
// Use decorators if needed
@observer
export 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 (
  <form style={formStyle} onSubmit={props.onSubmit}>
   {props.children}
   <button onClick={props.onExpand}>Expand</button>
  </form>
 )
}
登录后复制

我们的组件是一个方法。它的参数就是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 (
  <form style={formStyle} onSubmit={onSubmit}>
   {children}
   <button onClick={onExpand}>Expand</button>
  </form>
 )
}
登录后复制

现在我们也可以使用默认参数来扮演默认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 (
  <form style={formStyle} onSubmit={onSubmit}>
   {children}
   <button onClick={onExpand}>Expand</button>
  </form>
 )
}
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 dependencies
import './styles/Form.css'
// Declare propTypes here, before the component (taking advantage of JS function hoisting)
// You want these to be as visible as possible
ExpandableForm.propTypes = {
 onSubmit: func.isRequired,
 expanded: bool,
 onExpand: func.isRequired
}
// Destructure props like so, and use default arguments as a way of setting defaultProps
function ExpandableForm({ onExpand, expanded = false, children, onSubmit }) {
 const formStyle = expanded ? { height: 'auto' } : { height: 0 }
 return (
  <form style={formStyle} onSubmit={onSubmit}>
   {children}
   <button onClick={onExpand}>Expand</button>
  </form>
 )
}
// Wrap the component instead of decorating it
export default observer(ExpandableForm)
登录后复制

条件判断

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

<p id="lb-footer">
 {props.downloadMode && currentImage && !currentImage.video && currentImage.blogText
 ? !currentImage.submitted && !currentImage.posted
 ? <p>Please contact us for content usage</p>
  : currentImage && currentImage.selected
   ? <button onClick={props.onSelectImage} className="btn btn-selected">Deselect</button>
   : currentImage && currentImage.submitted
    ? <button className="btn btn-submitted" disabled>Submitted</button>
    : currentImage && currentImage.posted
     ? <button className="btn btn-posted" disabled>Posted</button>
     : <button onClick={props.onSelectImage} className="btn btn-unselected">Select post</button>
 }
</p>
登录后复制

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

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

<p id="lb-footer">
 {
  (() => {
   if(downloadMode && !videoSrc) {
    if(isApproved && isPosted) {
     return <p>Right click image and select "Save Image As.." to download</p>
    } else {
     return <p>Please contact us for content usage</p>
    }
   }
   // ...
  })()
 }
</p>
登录后复制

相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!

推荐阅读:

JsChart的组件使用详解

JS的图片处理与合成详解

以上是React组件的使用详解的详细内容。更多信息请关注PHP中文网其他相关文章!

本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

AI Hentai Generator

AI Hentai Generator

免费生成ai无尽的。

热门文章

R.E.P.O.能量晶体解释及其做什么(黄色晶体)
2 周前 By 尊渡假赌尊渡假赌尊渡假赌
仓库:如何复兴队友
4 周前 By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island冒险:如何获得巨型种子
3 周前 By 尊渡假赌尊渡假赌尊渡假赌

热工具

记事本++7.3.1

记事本++7.3.1

好用且免费的代码编辑器

SublimeText3汉化版

SublimeText3汉化版

中文版,非常好用

禅工作室 13.0.1

禅工作室 13.0.1

功能强大的PHP集成开发环境

Dreamweaver CS6

Dreamweaver CS6

视觉化网页开发工具

SublimeText3 Mac版

SublimeText3 Mac版

神级代码编辑软件(SublimeText3)

如何安装Win10旧版本组件DirectPlay 如何安装Win10旧版本组件DirectPlay Dec 28, 2023 pm 03:43 PM

不少用户在玩win10的的一些游戏的时候总是会遇到一些问题,比如说卡屏和花屏等等情况,这个时候我们是可以采用打开directplay这个功能来解决的,而且功能的操作方法也很简单。win10旧版组件directplay怎么安装1、在搜索框里面输入“控制面板”然后打开2、查看方式选择大图标3、找到“程序和功能”4、点击左侧的启用或关闭win功能5、选择旧版这里的勾选上就可以了

Win11管理员权限获取详解 Win11管理员权限获取详解 Mar 08, 2024 pm 03:06 PM

Windows操作系统是全球最流行的操作系统之一,其新版本Win11备受瞩目。在Win11系统中,管理员权限的获取是一个重要的操作,管理员权限可以让用户对系统进行更多的操作和设置。本文将详细介绍在Win11系统中如何获取管理员权限,以及如何有效地管理权限。在Win11系统中,管理员权限分为本地管理员和域管理员两种。本地管理员是指具有对本地计算机的完全管理权限

Oracle SQL中的除法运算详解 Oracle SQL中的除法运算详解 Mar 10, 2024 am 09:51 AM

OracleSQL中的除法运算详解在OracleSQL中,除法运算是一种常见且重要的数学运算操作,用于计算两个数相除的结果。除法在数据库查询中经常用到,因此了解OracleSQL中的除法运算及其用法是数据库开发人员必备的技能之一。本文将详细讨论OracleSQL中除法运算的相关知识,并提供具体的代码示例供读者参考。一、OracleSQL中的除法运算

Angular组件及其显示属性:了解非block默认值 Angular组件及其显示属性:了解非block默认值 Mar 15, 2024 pm 04:51 PM

Angular框架中组件的默认显示行为不是块级元素。这种设计选择促进了组件样式的封装,并鼓励开发人员有意识地定义每个组件的显示方式。通过显式设置CSS属性 display,Angular组件的显示可以完全控制,从而实现所需的布局和响应能力。

如何打开win10旧版组件的设置 如何打开win10旧版组件的设置 Dec 22, 2023 am 08:45 AM

win10旧版组件是需要用户自己去设置里面打开的,因为很多的组件平时都是默认关闭的状态,首先我们需要进入到设置里面,操作很简单,跟着下面的步骤来就可以了win10旧版组件在哪里打开1、点击开始,然后点击“win系统”2、点击进入控制面板3、再点击下面的程序4、点击“启用或关闭win功能”5、在这里就可以选择你要的打开了

PHP模运算符的作用及用法详解 PHP模运算符的作用及用法详解 Mar 19, 2024 pm 04:33 PM

PHP中的模运算符(%)是用来获取两个数值相除的余数的。在本文中,我们将详细讨论模运算符的作用及用法,并提供具体的代码示例来帮助读者更好地理解。1.模运算符的作用在数学中,当我们将一个整数除以另一个整数时,会得到一个商和一个余数。例如,当我们将10除以3时,商为3,余数为1。模运算符就是用来获取这个余数的。2.模运算符的用法在PHP中,使用%符号来表示模

linux系统调用system()函数详解 linux系统调用system()函数详解 Feb 22, 2024 pm 08:21 PM

Linux系统调用system()函数详解系统调用是Linux操作系统中非常重要的一部分,它提供了一种与系统内核进行交互的方式。其中,system()函数是一个常用的系统调用函数之一。本文将详细介绍system()函数的使用方法,并提供相应的代码示例。系统调用的基本概念系统调用是用户程序与操作系统内核交互的一种方式。用户程序通过调用系统调用函数来请求操作系统

Java框架与前端React框架的整合 Java框架与前端React框架的整合 Jun 01, 2024 pm 03:16 PM

Java框架与React框架的整合:步骤:设置后端Java框架。创建项目结构。配置构建工具。创建React应用。编写RESTAPI端点。配置通信机制。实战案例(SpringBoot+React):Java代码:定义RESTfulAPI控制器。React代码:获取并显示API返回的数据。

See all articles