iis服务器助手广告广告
返回顶部
首页 > 资讯 > 前端开发 > VUE >怎么编写react组件
  • 614
分享到

怎么编写react组件

2024-04-02 19:04:59 614人浏览 安东尼
摘要

这篇文章主要介绍“怎么编写React组件”,在日常操作中,相信很多人在怎么编写react组件问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法,希望对大家解答”怎么编写react组件”的疑惑有所帮

这篇文章主要介绍“怎么编写React组件”,在日常操作中,相信很多人在怎么编写react组件问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法,希望对大家解答”怎么编写react组件”的疑惑有所帮助!接下来,请跟着小编一起来学习吧!

Class Based Components (基于类的组件)

Class based components 有自己的state和方法。我们会尽可能谨慎的使用这些组件,但是他们有自己的使用场景。

接下来我们就一行一行来编写组件。

导入CSS

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

我很喜欢CSS in js,但是它目前还是一种新的思想,成熟的解决方案还未产生。我们在每个组件中都导入了它的css文件。

译者注:目前CSS in JS可以使用css modules方案来解决,webpack的css-loader已经提供了该功能

我们还用一个空行来区分自己的依赖。

译者注:即第4、5行和第1、2行中间会单独加行空行。

初始化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,不过我们更喜欢这种简洁的方式。我们还会确保默认导出组件的class。

propTypes 和 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。你的所有组件,都应该有propTypes属性。

方法

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 })  }

使用class  components,当你向子组件传递方法的时候,需要确保这些方法被调用时有正确的this值。通常会在向子组件传递时使用this.handleSubmit.bind(this)来实现。当然,使用es6的箭头函数写法更加简洁。

译者注:也可以在constructor中完成方法的上下文的绑定:

constructor() {  this.handleSubmit = this.handleSubmit.bind(this);  }

给setState传入一个函数作为参数(passing setState a Function)

在上文的例子中,我们是这么做的:

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

setState实际是异步执行的,react因为性能原因会将state的变化整合,再一起处理,因此当setState被调用的时候,state并不一定会立即变化。

这意味着在调用setState的时候你不能依赖当前的state值——因为你不能确保setState真正被调用的时候state究竟是什么。

解决方案就是给setState传入一个方法,该方法接收上一次的state作为参数。

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

解构props

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 (        <ExpandableForm          onSubmit={this.handleSubmit}          expanded={this.state.expanded}          onExpand={this.handleExpand}>         <div>           <h2>{title}</h2>           <input             type="text"             value={model.name}             onChange={this.handleNameChange}             placeholder="Your Name"/>         </div>       </ExpandableForm>     )   } }

对于有很多props的组件来说,应当像上述写法一样,将每个属性解构出来,且每个属性单独一行。

装饰器(Decorators)

@observer  export default class ProfileContainer extends Component {

如果你正在使用类似于mobx的状态管理器,你可以按照上述方式描述你的组件。这种写法与将组件作为参数传递给一个函数效果是一样的。装饰器(decorators)是一种非常灵活和易读的定义组件功能的方式。我们使用mobx和mobx-models来结合装饰器进行使用。

如果你不想使用装饰器,可以按照如下方式来做:

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

闭包

避免向子组件传入闭包,如下:

<input             type="text"             value={model.name}             // onChange={(e) => { model.name = e.target.value }}             // ^ 不要这样写,按如下写法:             onChange={this.handleChange}             placeholder="Your Name"/>

原因在于:每次父组件重新渲染时,都会创建一个新的函数,并传给input。

如果这个input是个react组件的话,这会导致无论该组件的其他属性是否变化,该组件都会重新render。

而且,采用将父组件的方法传入的方式也会使得代码更易读,方便调试,同时也容易修改。

完整代码如下:

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 (        <ExpandableForm          onSubmit={this.handleSubmit}          expanded={this.state.expanded}          onExpand={this.handleExpand}>         // Newline props if there are more than two         <div>           <h2>{title}</h2>           <input             type="text"             value={model.name}             // onChange={(e) => { model.name = e.target.value }}             // Avoid creating new closures in the render method- use methods like below             onChange={this.handleNameChange}             placeholder="Your Name"/>         </div>         </ExpandableForm>     )   } }

函数组件(Functional Components)

这些组件没有state和方法。它们是纯净的,非常容易定位问题,可以尽可能多的使用这些组件。

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,非常直观。我们可以这么做是因为js的函数名提升机制。

Destructuring Props and defaultProps(解构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>   ) }

我们可以给参数设置默认值,作为defaultProps。如果expanded是undefined,就将其设置为false。(这种设置默认值的方式,对于对象类的入参非常有用,可以避免`can't  read property XXXX of undefined的错误)

不要使用es6箭头函数的写法:

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

这种写法中,函数实际是匿名函数。如果正确地使用了babel则不成问题,但是如果没有,运行时就会导致一些错误,非常不方便调试。

另外,在Jest,一个react的测试库,中使用匿名函数也会导致一些问题。由于使用匿名函数可能会出现一些潜在的问题,我们推荐使用function,而不是const。

Wrapping

在函数组件中不能使用装饰器,我们可以将其作为入参传给observer函数

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)

完整组件如下所示:

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)

在JSX中使用条件判断(Conditionals in JSX)

有时候我们需要在render中写很多的判断逻辑,以下这种写法是我们应该要避免的:

怎么编写react组件

目前有一些库来解决这个问题,但是我们没有引入其他依赖,而是采用了如下方式来解决:

怎么编写react组件

这里我们采用立即执行函数的方式来解决问题,将if语句放到立即执行函数中,返回任何你想返回的。需要注意的是,立即执行函数会带来一定的性能问题,但是对于代码的可读性来说,这个影响可以忽略。

同样的,当你只希望在某种情况下渲染时,不要这么做:

{   isTrue    ? <p>True!</p>    : <none/> }

而应当这么做:

{  isTrue &&  <p>True!</p>  }

到此,关于“怎么编写react组件”的学习就结束了,希望能够解决大家的疑惑。理论与实践的搭配能更好的帮助大家学习,快去试试吧!若想继续学习更多相关知识,请继续关注编程网网站,小编会继续努力为大家带来更多实用的文章!

--结束END--

本文标题: 怎么编写react组件

本文链接: https://www.lsjlt.com/news/85993.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
  • 怎么编写react组件
    这篇文章主要介绍“怎么编写react组件”,在日常操作中,相信很多人在怎么编写react组件问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法,希望对大家解答”怎么编写react组件”的疑惑有所帮...
    99+
    2022-10-19
  • 怎么写出React组件
    这篇文章主要介绍“怎么写出React组件”,在日常操作中,相信很多人在怎么写出React组件问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法,希望对大家解答”怎么写出React组件”的疑惑有所帮助!接下来,请跟着小编一起来学习吧...
    99+
    2023-06-17
  • 编写简洁React组件的小技巧
    目录避免使用扩展操作符传递 props将函数参数封装成一个对象对于事件处理函数,将该处理函数作为函数的返回值组件渲染使用 map 而非 if/elseHook组件组件拆分使用包装器关...
    99+
    2022-11-12
  • 使用React组件编写温度显示器
    本文实例为大家分享了React组件编写温度显示器的具体代码,供大家参考,具体内容如下 这是模拟了一下温度显示器的效果,先看效果: 先在页面中引入React等; import Rea...
    99+
    2022-11-13
  • 怎么用TypeScript编写React
    本篇内容介绍了“怎么用TypeScript编写React”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有所成!Re...
    99+
    2022-10-19
  • react生命周期的类组件和函数组件怎么写
    这篇文章主要介绍“react生命周期的类组件和函数组件怎么写”,在日常操作中,相信很多人在react生命周期的类组件和函数组件怎么写问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法,希望对大家解答”react生命周期的类组件和函...
    99+
    2023-07-04
  • React组件怎么转Vue组件
    本篇内容主要讲解“React组件怎么转Vue组件”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“React组件怎么转Vue组件”吧!简介对于react-to-vu...
    99+
    2022-10-19
  • 怎么用Java编写ASP组件
    这篇文章主要介绍怎么用Java编写ASP组件,文中介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们一定要看完!  ASP通过ActiveX Server Components(ActiveX 服务器元件 ) 使其具有无限可扩充...
    99+
    2023-06-03
  • Java中怎么编写ASP组件
    今天就跟大家聊聊有关Java中怎么编写ASP组件,可能很多人都不太了解,为了让大家更加了解,小编给大家总结了以下内容,希望大家根据这篇文章可以有所收获。先写个很简单的Java程序public class TestJava{public St...
    99+
    2023-06-03
  • React组件的三种写法是什么
    这篇文章将为大家详细讲解有关React组件的三种写法是什么,小编觉得挺实用的,因此分享给大家做个参考,希望大家阅读完这篇文章后可以有所收获。React 专注于 view 层,组件化则是 React 的基础,...
    99+
    2022-10-19
  • React组件的写法有哪些
    这篇文章给大家分享的是有关React组件的写法有哪些的内容。小编觉得挺实用的,因此分享给大家做个参考,一起跟随小编过来看看吧。React 专注于 view 层,组件化则是 React 的基础,也是其核心理念...
    99+
    2022-10-19
  • JavaScript中React面向组件编程怎么使用
    这篇文章主要介绍“JavaScript中React面向组件编程怎么使用”,在日常操作中,相信很多人在JavaScript中React面向组件编程怎么使用问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法,希望对大家解答”JavaS...
    99+
    2023-07-05
  • 如何写出漂亮的React组件
    如何写出漂亮的React组件,针对这个问题,这篇文章详细介绍了相对应的分析和解答,希望可以帮助更多想解决这个问题的小伙伴找到更简单易行的方法。在Walmart Labs的产品开发中,我们进行了大量的Code...
    99+
    2022-10-19
  • 怎么编写更好的React代码
    这篇文章主要介绍“怎么编写更好的React代码”,在日常操作中,相信很多人在怎么编写更好的React代码问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法,希望对大家解答”怎么编写更好的React...
    99+
    2022-10-19
  • React组件间怎么通信
    本文小编为大家详细介绍“React组件间怎么通信”,内容详细,步骤清晰,细节处理妥当,希望这篇“React组件间怎么通信”文章能帮助大家解决疑惑,下面跟着小编的思路慢慢深入,一起来学习新知识吧。一、父子组件...
    99+
    2022-10-19
  • react native怎么隐藏组件
    本教程操作环境:Windows10系统、react18.0.0版、Dell G3电脑。react native 中如何对组件进行隐藏?具体问题描述:如何通过A中的switchAndroid的value来控制B模块的显示和隐藏呢显示全部问题解...
    99+
    2023-05-14
    组件 react-native
  • React怎么封装SvgIcon组件
    本篇内容介绍了“React怎么封装SvgIcon组件”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有所成!React优雅的封装SvgIcon组件相信...
    99+
    2023-07-05
  • React函数组件与类组件怎么使用
    这篇“React函数组件与类组件怎么使用”文章的知识点大部分人都不太理解,所以小编给大家总结了以下内容,内容详细,步骤清晰,具有一定的借鉴价值,希望大家阅读完这篇文章能有所收获,下面我们一起来看看这篇“React函数组件与类组件怎么使用”文...
    99+
    2023-06-30
  • react dva实现的代码怎么编写
    今天就跟大家聊聊有关react dva实现的代码怎么编写,可能很多人都不太了解,为了让大家更加了解,小编给大家总结了以下内容,希望大家根据这篇文章可以有所收获。dvadva是一个基于redux和redux-saga的数据流方案,然后为了简化...
    99+
    2023-06-25
  • html组件怎么写
    这篇“html组件怎么写”文章的知识点大部分人都不太理解,所以小编给大家总结了以下内容,内容详细,步骤清晰,具有一定的借鉴价值,希望大家阅读完这篇文章能有所收获,下面我们一起来看看这篇“html组件怎么写”...
    99+
    2022-10-19
软考高级职称资格查询
推荐阅读
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作