react 渲染道具

by Evelyn Chan

通过伊芙琳·陈

在React中学习分解道具的基础 (Learn the basics of destructuring props in React)

When I first learned about ES6, I was hesitant to start using it. I’d heard a lot of great things about the improvements but at the same time, I’d just gotten used to the good ol’ original way of doing things and here was a new syntax thrown at me to learn.

当我第一次了解ES6时,我犹豫要开始使用它。 我听到了很多有关改进的很棒的事情,但是与此同时,我只是习惯了良好的原始工作方式,这是我学习的一种新语法。

I avoided it for a while under the premise of “if it ain’t broke don’t fix it,” but I’ve recently grown fond of its simplicity and the fact that it’s becoming the norm in JavaScript.

我曾在“如果它还没有坏,就不修复它”的前提下避免了一段时间,但是我最近对它的简单性以及它已经成为JavaScript的规范感到很喜欢。

With React, which fully embraces the ES6 syntax, destructuring adds a slew of benefits to improving your code. This article will go over the basics of destructuring objects and how it applies to props in React.

使用完全包含ES6语法的React,解构可以为改进代码带来很多好处。 本文将介绍解构对象的基础知识以及如何将其应用于React中的props。

破坏的原因 (Reasons to destructure)

提高可读性 (Improves readability)

This is a huge upside in React when you’re passing down props. Once you take the time to destructure your props, you can get rid of props / this.props in front of each prop.

当您传递道具时,这在React中是巨大的优势。 一旦您花时间破坏了道具,就可以在每个道具的前面摆脱props / this.props

If you’re abstracting your components into different files, you’ll also have a handy place to quickly reference what props you’re passing down without having to switch tabs. This double check helps you catch errors such as passing down excess props or typos.

如果要将组件抽象到不同的文件中,则还可以方便地快速引用要传递的道具,而无需切换选项卡。 这项双重检查可帮助您捕获错误,例如传递过多的道具或错别字。

You can go a step further by adding in propType validation, which allows you to define the type of each prop you pass in. When you’re in a development environment, this triggers React to log a warning if the type is different from the one defined.

您可以通过添加propType验证来propType ,它允许您定义传入的每个prop的类型。在开发环境中时,如果类型不同于一个,则触发React记录警告。定义。

Props can be difficult to keep track of in complex apps, so clearly defining your props as you pass them down is immensely helpful for anyone reading your code.

在复杂的应用程序中,道具可能很难跟踪,因此在向下传递道具时清楚地定义道具对于任何阅读代码的人都非常有帮助。

较短的代码行 (Shorter lines of code)

See the following before ES6:

在ES6之前,请参阅以下内容:

var object = { one: 1, two: 2, three: 3 }
var one = object.one;var two = object.two;var three = object.three
console.log(one, two, three) // prints 1, 2, 3

It’s long, clunky, and takes way too many lines of code. With destructuring, your code becomes much more clear.

它很长,很笨拙,并且占用了太多的代码行。 通过解构,您的代码变得更加清晰。

In the example below, we’ve effectively cut down the number of lines to two:

在下面的示例中,我们有效地将行数减少为两行:

let object = { one: 1, two: 2, three: 3 }
let { one, two, three } = object;
console.log(one, two, three) // prints 1, 2, 3

句法糖 (Syntactic sugar)

It makes code look nicer, more succinct, and like someone who knows what they’re doing wrote it. I’m somewhat reiterating the first point here, but then again if it improves readability, why wouldn’t you do it?

它使代码看起来更好,更简洁,就像知道自己在做什么的人一样。 我在这里重申了第一点,但是如果它提高了可读性,那么再来一次,您为什么不这样做呢?

功能与类组件 (Functional vs. Class Components)

Destructuring in React is useful for both functional and class components but is achieved just a tad bit differently.

React中的解构对于功能组件和类组件都是有用的,但是在实现上却有所不同。

Let’s consider a parent component in our application:

让我们考虑一下应用程序中的父组件:

import React, { Component } from 'react';
class Properties extends Component {  constructor() {    super();    this.properties = [      {        title: 'Modern Loft',        type: 'Studio',        location: {          city: 'San Francisco',          state: 'CA',          country: 'USA'        }      },      {        title: 'Spacious 2 Bedroom',        type: 'Condo',        location: {          city: 'Los Angeles',          state: 'CA',          country: 'USA'        }      },    ];  }
render() {    return (      <div>        <Listing listing={this.properties[0]} />        <Listing listing={this.properties[1]} />      </div>    );  }}

功能组件 (Functional Components)

In this example, we want to pass down a listing object from our array of properties for the child component to render.

在此示例中,我们希望从属性数组中传递一个listing对象,以供子组件呈现。

Here’s how a functional component would look:

这是功能组件的外观:

const Listing = (props) => (  <div>    <p>Title: {props.listing.title}</p>    <p>Type: {props.listing.type}</p>    <p>      Location: {props.listing.location.city},      {props.listing.location.state},      {props.listing.location.country}    </p>  </div>);

This block of code is fully functional but looks terrible! By the time we get to this Listing child component, we already know we’re referencing a listing, so props.listing looks and feels redundant. This block of code can be made to look much cleaner through destructuring.

此代码块功能齐全,但看起来很糟糕! 当我们到达这个Listing子组件时,我们已经知道我们正在引用一个清单,因此props.listing看起来和感觉都是多余的。 通过解构,可以使这段代码看起来更简洁。

We can achieve this in the function parameter as we pass in the props argument:

我们可以在传递props参数时在function参数中实现此目的:

const Listing = ({ listing }) => (  <div>    <p>Title: {listing.title}</p>    <p>Type: {listing.type}</p>    <p>      Location: {listing.location.city},      {listing.location.state},      {listing.location.country}    </p>  </div>);

Even better, we can further destructure nested objects like below:

更好的是,我们可以进一步分解嵌套对象,如下所示:

const Listing = ({  listing: {    title,    type,    location: {      city,      state,      country    }  }}) => (  <div>    <p>Title: {title}</p>    <p>Type: {type}</p>    <p>Location: {city}, {state}, {country}</p>  </div>);

Can you see how much easier this is to read? In this example, we’ve destructured both listings and the keys inside listing.

您能看到这更容易阅读吗? 在此示例中,我们对listingslistings的键进行了listing

A common gotcha is destructuring only the keys like we do below and trying to access the object:

一个常见的陷阱是仅对键进行解构,就像我们在下面所做的那样,并尝试访问该对象:

{ location: { city, state, country } }

In this scenario, we wouldn’t be able to access the location object through a variable named location.

在这种情况下,我们将无法通过名为location的变量访问location对象。

In order to do so, we’d have to define it first with a simple fix like so:

为了做到这一点,我们必须首先用一个简单的解决方法定义它,如下所示:

{ location, location: { city, state, country } }

This wasn’t glaringly obvious to me at first, and I’d occasionally run into problems if I wanted to pass an object like location as a prop after destructuring its contents. Now you’re equipped to avoid the same mistakes I made!

一开始这对我来说并不是显而易见的,而且如果我想在分解内容之后将location类的对象作为道具传递给我,偶尔会遇到麻烦。 现在您已准备好避免我犯的相同错误!

类组件 (Class Components)

The idea is very much the same in class components, but the execution is a little different.

这个想法在类组件中几乎是相同的,但是执行有些不同。

Take a look below:

看下面:

import React, { Component } from 'react';
class Listing extends Component {  render() {    const {      listing: {        title,        type,        location: {          city,          state,          country        }      }    } = this.props;
return (      <div>        <p>Title: {title}</p>        <p>Type: {type}</p>        <p>          Location: {city}, {state}, {country}        </p>      </div>    )  }}

You may have noticed in the parent example that we can destructure the Component object as we import React in class components. This isn’t necessary for functional components as we won’t be extending the Component class for those.

您可能已经在父示例中注意到,当我们在类组件中导入React ,我们可以对Component对象进行解构。 对于功能组件,这不是必需的,因为我们不会为这些Component扩展Component类。

Next, instead of destructuring in the argument, we destructure wherever the variables are being called. For example, if we take the same Listing child component and refactor it into a class, we would destructure in the render function where the props are being referenced.

接下来,我们将在调用变量的任何位置进行销毁,而不是对参数进行销毁。 例如,如果我们使用相同的Listing子组件并将其重构为一个类,我们将在引用道具的render函数中对结构进行分解。

The downside to destructuring in class components is that you’ll end up destructuring the same props each time you use it in a method. Although this can be repetitive, I’d argue that a positive is it clearly outlines which props are being used in each method.

在类组件中进行结构分解的不利之处在于,每次在方法中使用它时,最终都会破坏相同的道具。 尽管这可能是重复的,但我认为肯定的是,它清楚地概述了每种方法中使用的道具。

In addition, you won’t have to worry about side effects such as accidentally changing a variable reference. This method keeps your methods separate and clean, which can be a huge advantage for other operations during your projects such as debugging or writing tests.

此外,您不必担心副作用,例如意外更改变量引用。 此方法使您的方法保持独立和整洁,这对于项目中的其他操作(例如调试或编写测试)可能是一个巨大的优势。

Thanks for reading! If this helped you, please clap and/or share this article so it can help others too! :)

谢谢阅读! 如果这对您有帮助,请拍手和/或分享此文章,以便对他人也有所帮助! :)

翻译自: https://www.freecodecamp.org/news/the-basics-of-destructuring-props-in-react-a196696f5477/

react 渲染道具

react 渲染道具_在React中学习分解道具的基础相关推荐

  1. react 渲染道具_关于React道具的另一篇文章

    react 渲染道具 You could say this topic has been done to death, but lately I've started using a techniqu ...

  2. react 最佳实践_最佳React教程

    react 最佳实践 React is a JavaScript library for building user interfaces. It was voted the most loved i ...

  3. react实现汉堡_利用 React 高阶组件实现一个面包屑导航

    什么是 React 高阶组件 React 高阶组件就是以高阶函数的方式包裹需要修饰的 React 组件,并返回处理完成后的 React 组件.React 高阶组件在 React 生态中使用的非常频繁, ...

  4. react 组件构建_为React构建星级评定组件

    react 组件构建 Who doesn't love beer? When you drink a great beer you want to tell someone. You definite ...

  5. python教程培训福永_在玩耍中学习英语-杜丫丫AI智能英语早教机体验分享

    在玩耍中学习英语-杜丫丫AI智能英语早教机体验分享 2019-07-12 19:56:09 8点赞 8收藏 17评论 不知道什么时候开始,开始学习英语的年龄已经从我们这一代的小学,提前到了现在的胎教. ...

  6. react 组件构建_使用React Spring和Tinycolor构建色彩丰富的弹性组件

    react 组件构建 Recently, I decided to build a web application to allow designers and developers to gener ...

  7. react待办事项_使用React创建一个简单的待办应用

    react待办事项 You could be wondering what is so special about React; What we will do is pick up from a p ...

  8. react http请求_当React开发者初次走进React-Native的世界

    RN千机变 1.技术体系问题 RN和React共用一套抽象层,相对于前端,RN其实更接近Node的运行环境 ReactNative =React +IOS +Android 看RN文档时,我会发现入门 ...

  9. react ui框架_顶级React组件库推荐

    作者丨Max Rozen 译者丨王强 策划丨小智 转发链接:https://mp.weixin.qq.com/s/-vRr8Qd8DCNiza09eZjmbQ 本文最初发布于 maxrozen.com ...

最新文章

  1. 美国人到底为什么不待见人脸识别技术?
  2. ExtJS grid简单应用之 展示JSON数据
  3. 企业版Java EE正式易主 甲骨文再次放手
  4. 在C#中利用DirectX实现声音播放
  5. 父盒子高度为子盒子总高度自动撑满 height: fit-content; //设置内容高度
  6. 陕师大计算机科学学院研究生,陕师大研究生
  7. 不贵难得之货,使民不盗
  8. 趣味图解 | 什么是缺页错误 Page Fault?
  9. SpringBoot控制层页面指定返回html前端页面
  10. 比特币以太坊数字货币钱包安全助记词安全问题
  11. 为什么Audition CC2017扫描不了电音插件,你需要这个工具
  12. jQueryWEUI自定义对话框-带有textarea
  13. 服装尺寸 html,服装尺寸S、M、L、XL、XXL分别表示的型号大小和释义(完整版)...
  14. 为什么神经网络有偏置? 神经网络中的偏置(bias)究竟有这么用
  15. MATLAB矩阵相关函数学习--中级函数
  16. Transformer课程 第8课 NER案例模型训练及预测
  17. 【CSS 颜色的 合法颜色值 (详细介绍)】
  18. css里面的网格布局
  19. linux 怎么看浏览器,Linux下浏览器比比看
  20. Jetson-nano:制作TF卡启动

热门文章

  1. FileInfo类 c# 1614533684
  2. 标识符的命名规定java 0126
  3. 默写标准答案0917
  4. 办公自动化-表格的读写操作-xlrd-xlwt
  5. git-注册与激活-创建一个测试用途的仓库-github
  6. django-自定义错误页面-404
  7. mysql-外键-随堂
  8. Oracle GoldenGate For Big Data - Kafka Handler
  9. Unity应用架构设计(10)——绕不开的协程和多线程(Part 1)
  10. 评分组件(RatingBar)