php 空间类元素引入_引入单元素模式

php 空间类元素引入

by Diego Haz

迭戈·哈兹(Diego Haz)

引入单元素模式 (Introducing the Single Element Pattern)

使用React和其他基于组件的库创建可靠的构建基块的规则和最佳实践。 (Rules and best practices for creating reliable building blocks with React and other component-based libraries.)

Back in 2002 — when I started building stuff for the web — most developers, including me, structured their layouts using <table> tags.

早在2002年(当我开始为Web构建东西时),包括我在内的大多数开发人员都使用<tab le>标签构造了其布局。

Only in 2005 did I start following web standards.

仅在2005年,我才开始遵循Web标准

When a web site or web page is described as complying with web standards, it usually means that the site or page has valid HTML, CSS and JavaScript. The HTML should also meet accessibility and semantic guidelines.
当网站或网页被描述为符合网络标准时,通常意味着该网站或网页具有有效HTML,CSS和JavaScript。 HTML还应该符合可访问性和语义准则。

I learned about semantics and accessibility, then started to use proper HTML tags and external CSS. I was proudly adding those W3C Badges to every web site I made.

我了解了语义和可访问性,然后开始使用适当HTML标记和外部CSS。 我很自豪地将那些W3C徽章添加到我创建的每个网站中。

The HTML code we wrote was pretty much the same as the output code that went to the browser. That means that validating our output using the W3C Validator and other tools was also teaching us how to write better code.

我们编写HTML代码与浏览器的输出代码几乎相同。 这意味着使用W3C验证器和其他工具验证我们的输出还教会了我们如何编写更好的代码。

Time has passed. To isolate reusable parts of the front end, I've used PHP, template systems, jQuery, Polymer, Angular, and React. This latter, in particular, I have been using for the past three years.

时间已经过去了。 为了隔离前端的可重用部分,我使用了PHP,模板系统,jQuery,Polymer,Angular和React。 尤其是后者,我在过去三年中一直在使用。

As time went on, the code we wrote was getting more and more different from the one served to the user. Nowadays, we’re transpiling our code in many different ways (using Babel and TypeScript, for example). We write ES2015+ and JSX, but the output code will be just HTML and JavaScript.

随着时间的流逝,我们编写的代码与提供给用户的代码越来越不同。 如今,我们以许多不同的方式(例如,使用Babel和TypeScript)来转换代码。 我们编写ES2015 +JSX ,但是输出代码将只是HTML和JavaScript。

Currently, even though we can still use W3C tools to validate our web sites, they don't help us much with the code we write. We're still pursuing best practices to make our code more consistent and maintainable. And, if you're reading this article, I guess you're also looking for the same thing.

当前,即使我们仍然可以使用W3C工具来验证我们的网站,但它们对我们编写的代码没有太大帮助。 我们仍在追求最佳实践,以使我们的代码更加一致和可维护。 而且,如果您正在阅读本文,我想您也在寻找相同的东西。

And I have something for you.

我有东西要给你。

单元素模式( Singel ) (The Single Element Pattern (Singel))

I don't know exactly how many components I've written so far. But, if I put Polymer, Angular and React together, I can safely say that this number is over a thousand.

我不知道到目前为止我已经写了多少个组件。 但是,如果将Polymer,Angular和React放在一起,我可以放心地说这个数字超过了1000。

Besides company projects, I maintain a React boilerplate with more than 40 example components. Also, I'm working with Raphael Thomazella, who also contributed to this idea, on a UI toolkit with dozens more of them.

除了公司项目,我还维护一个带有40多个示例组件的React样板 。 另外,我正在与Raphael Thomazella一起工作,他也为这个想法做出了贡献,并在UI工具包中提供了数十种工具

Many developers have the misconception that, if they start a project with the perfect file structure, they'll have no problems. The reality, though, is that it doesn't matter how consistent your file structure is. If your components don't follow well-defined rules, this will eventually make your project hard to maintain.

许多开发人员误以为,如果他们以一个完美的文件结构开始一个项目,他们将不会有任何问题。 但是,现实情况是文件结构的一致性并不重要。 如果您的组件没有遵循明确定义的规则,那么最终将使您的项目难以维护。

After creating and maintaining so many components, I can identify some characteristics that made them more consistent and reliable and, therefore, more enjoyable to use. The more a component resembled an HTML element, the more reliable it became.

创建并维护了如此多的组件之后,我可以确定一些使它们更一致和更可靠,因此使用起来更有趣的特征。 组件越类似于HTML元素,它就变得越可靠

There's nothing more reliable than a <div>.

没有什么比<d iv>更可靠的了。

When using a component, you'll ask yourself one or more of these questions:

使用组件时,您将问自己一个或多个以下问题:

  • Question #1: What if I need to pass props to nested elements?

    问题1:如果我需要将prop传递给嵌套元素怎么办?
  • Question #2: Will this break the app for some reason?

    问题2:这会因为某种原因而中断应用程序吗?
  • Question #3: What if I want to pass id or another HTML attribute?

    问题3:如果我想传递id或其他HTML属性怎么办?

  • Question #4: Can I style it passing className or style props?

    问题4:我可以通过classNamestyle道具来设置style吗?

  • Question #5: What about event handlers?

    问题5:事件处理程序如何?

Reliability means, in this context, not needing to open the file and look at the code to understand how it works. If you're dealing with a <div>, for example, you'll know the answers right away:

在这种情况下, 可靠性意味着不需要打开文件并查看代码来了解其工作原理。 例如,如果您正在处理<d iv>,您将立即知道答案:

This is the group of rules that we call Singel.

这就是我们称为Singel的一组规则。

重构驱动的开发 (Refactor-driven development)

Make it work, then make it better.
使它工作,然后使其更好。

Of course, it's not possible to have all of your components following Singel. At some point — in fact, at many points — you'll have to break at least the first rule.

当然,不可能让所有组件都遵循Singel 。 在某些时候(实际上在很多时候),您至少必须打破第一条规则。

The components that should follow these rules are the most important part of your application: atoms, primitives, building blocks, elements or whatever you call your foundation components. In this article, I'm going to call them single elements.

遵循这些规则的组件是应用程序中最重要的部分:原子,基元,构建块,元素或您称为基础组件的任何组件。 在本文中,我将其称为单个元素

Some of them are easy to abstract right away: Button, Image, Input. That is, those components that have a direct relationship with HTML elements. In some other cases, you'll only identify them when you start having to duplicate code. And that's fine.

其中一些很容易立即抽象: ButtonImageInput 。 也就是说,那些与HTML元素有直接关系的组件。 在其他情况下,只有在开始重复代码时才可以识别它们。 很好。

Often, whenever you need to change some component, add a new feature, or fix a bug, you'll see — or start writing — duplicated styling and behavior. That's the signal to abstract it into a new single element.

通常,每当需要更改某些组件,添加新功能或修复错误时,您都会看到(或开始编写)重复的样式和行为。 这是将其抽象为新的单个元素的信号。

The higher the percentage of single elements in your application compared to other components, the more consistent and easier to maintain it will be.

与其他组件相比,应用程序中的单个元素所占的百分比越高,它将越一致且易于维护。

Put them into a separate folder — elements, atoms, primitives — so, whenever you import some component from it, you'll be sure about the rules it follows.

将它们放到一个单独的文件夹中elementsatomsprimitives -因此,每当从其中导入某些组件时,您都将确定遵循的规则。

一个实际的例子 (A practical example)

In this article I’m focussing on React. The same rules can be applied to any component-based library out there.

在本文中,我将重点介绍React。 相同的规则可以应用于任何基于组件的库。

That said, consider that we have a Card component. It's composed of Card.js and Card.css, where we have styles for .card, .top-bar, .avatar, and other class selectors.

也就是说,请考虑我们有一个Card组件。 它由Card.jsCard.css组成,其中我们具有.card.card .top-bar.avatar和其他类选择器的样式。

At some point, we have to put the avatar in another part of the application. Instead of duplicating HTML and CSS, we're going to create a new single element Avatar so we can reuse it.

在某些时候,我们必须将化身放在应用程序的另一部分中。 除了复制HTML和CSS之外,我们将创建一个新的单个元素Avatar以便我们可以重复使用它。

规则1:仅渲染一个元素 (Rule 1: Render only one element)

It's composed by Avatar.js and Avatar.css, which has the .avatar style we extracted from Card.css. This renders just an <img>:

它由Avatar.jsAvatar.css组成,它们具有从Card.css提取的.avatar样式。 这仅呈现<i mg>:

This is how we would use it inside Card and other parts of the application:

这就是我们在Card和应用程序其他部分中使用它的方式:

<Avatar profile={profile} />
规则2:永远不要破坏应用程序 (Rule 2: Never break the app)

An <img> doesn't break the app if you don't pass a src attribute, even though that's a required one. Our component, however, will break the whole app if we don't pass profile.

一个<i毫克>如果你不这样做p没有打破应用ass src属性,尽管这是一个需要一个。 但是,如果不pass p ,我们的组件将破坏整个应用程序。

React 16 provides a new lifecycle method called componentDidCatch, which can be used to gracefully handle errors inside components. Even though it's a good practice to implement error boundaries within your app, it may mask bugs inside our single element.

React 16提供了一个新的生命周期方法,称为componentDidCatch ,可以用来优雅地处理组件内部的错误。 即使在您的应用中实现错误边界是一种很好的做法,但它可能掩盖了我们单个元素中的错误。

We must make sure that Avatar is reliable by itself, and assume that even required props may not be provided by a parent component. In this case, besides checking whether profile exists before using it, we should use Flow, TypeScript, or PropTypes to warn about it:

我们必须确保Avatar本身是可靠的,并假设父组件甚至不能提供所需的道具。 在这种情况下,除了在使用profile之前检查profile是否存在之外,我们还应该使用FlowTypeScriptPropTypes进行警告:

Now we can render <Avatar /> with no props and see on the console what it expects to receive:

现在,我们可以在没有道具的情况下渲染<Avatar />,并在控制台上查看它希望收到的内容:

Often, we ignore those warnings and let our console accumulate several of them. This makes PropTypes useless, since we'll likely never notice new warnings when they show up. So, make sure to always solve the warnings before they multiply.

通常,我们会忽略这些警告,而让控制台累积其中的一些警告。 这使PropTypes无用,因为当它们出现时我们可能永远不会注意到新的警告。 因此,请确保始终解决警告,然后再进行警告。

规则3:呈现作为道具传递的所有HTML属性 (Rule 3: Render all HTML attributes passed as props)

So far, our single element was using a custom prop called profile. We should avoid using custom props, especially when they're mapped directly to HTML attributes. Learn more about it below, in Suggestion #1: Avoid adding custom props.

到目前为止,我们的单个元素正在使用名为profile的自定义道具。 我们应该避免使用自定义道具,尤其是当它们直接映射到HTML属性时。 请在建议1:以下中了解有关此内容的更多信息:避免添加自定义道具

We can easily accept all HTML attributes in our single elements by just passing all props down to the underlying element. We can solve the problem with custom props by expecting the respective HTML attributes instead:

通过将所有props向下传递到底层元素,我们可以轻松地接受单个元素中的所有HTML属性。 我们可以通过使用相应HTML属性来解决自定义道具的问题:

Now Avatar looks more like an HTML element:

现在, Avatar看起来更像一个HTML元素:

<Avatar src={profile.photoUrl} alt={profile.photoAlt} />

This rule also includes rendering children when, of course, the underlying HTML element accepts it.

当然,该规则还包括在基础HTML元素接受children时呈现children

规则4:始终合并作为道具传递的样式 (Rule 4: Always merge the styles passed as props)

Somewhere in your application, you'll want the single element to have a slightly different style. You should be able to customize it whether by using className or style props.

在应用程序中的某个位置,您将希望单个元素的样式略有不同。 您应该能够通过使用classNamestyle props对其进行自定义。

The internal style of a single element is equivalent to the style that browsers apply to native HTML elements. That being said, our Avatar, when receiving a className prop, shouldn't replace the internal one — but append it.

单个元素的内部样式等效于浏览器应用于本机HTML元素的样式。 话虽如此,我们的Avatar在收到className道具时,不应替换内部的道具,而应该附加它。

If we applied an internal style prop to Avatar, it could be easily solved by using object spread:

如果我们将内部style道具应用于Avatar ,则可以使用对象传播轻松解决:

Now we can reliably apply new styles to our single element:

现在,我们可以可靠地将新样式应用于单个元素:

<Avatar  className="my-avatar"  style={{ borderWidth: 1 }}/>

If you find yourself having to duplicate the new styles, don't hesitate to create another single element composing Avatar. It's fine — and often necessary — to create a single element that renders another single element.

如果您发现自己必须复制新样式,请毫不犹豫地创建另一个组成Avatar元素。 创建一个呈现另一个元素的元素很好,并且通常是必要的。

规则5:添加作为道具传递的所有事件处理程序 (Rule 5: Add all the event handlers passed as props)

Since we're passing all props down, our single element is already prepared to receive any event handler. However, if we already have that event handler applied internally, what should we do?

由于我们要传递所有props ,因此我们的单个元素已经准备好接收任何事件处理程序。 但是,如果已经在内部应用了该事件处理程序,该怎么办?

In this case, we have two options: we can replace the internal handler with the prop altogether, or call both. That's up to you. Just make sure to always apply the event handler coming from the prop.

在这种情况下,我们有两个选择:我们可以用prop替换内部处理程序,或者同时调用两者。 随你(由你决定。 只要确保始终应用来自prop的事件处理程序即可。

意见建议 (Suggestions)

建议1:避免添加自定义道具 (Suggestion 1: Avoid adding custom props)

When creating single elements — especially when developing new features in your application — you'll be tempted to add custom props in order to configure them in different ways.

当创建单个元素时,尤其是在应用程序中开发新功能时,您很容易添加自定义道具,以便以不同的方式对其进行配置。

Using Avatar as an example, by some eccentricity of the designer suppose you have some places where the avatar should be squared, and others where it should be rounded. You might think that it's a good idea to add a rounded prop to Avatar.

Avatar为例,以设计者的某些偏心性为前提,假设您在某些地方放置了化身,而在另一些地方则将其舍入。 您可能会认为向Avatar添加rounded道具是个好主意。

Unless you're creating a well-documented open source library, resist that. Besides introducing the need of documentation, it's not scalable and will lead to unmaintainable code. Always try to create a new single element — such as AvatarRounded — which renders Avatar and modifies it, rather than adding a custom prop.

除非你正在创建一个证据充分的开源库, 抵抗 。 除了引入文档需求之外,它还不能扩展,并且会导致代码无法维护。 始终尝试创建一个新的单个元素(例如AvatarRounded ,该元素将呈现Avatar并对其进行修改,而不是添加自定义道具。

If you keep using unique and descriptive names and building reliable components, you may have hundreds of them. It'll still be highly maintainable. Your documentation will be the names of the components.

如果您继续使用唯一的描述性名称并构建可靠的组件,则可能有数百个。 它仍然是高度可维护的。 您的文档将是组件的名称。

建议2:接收基础HTML元素作为道具 (Suggestion 2: Receive the underlying HTML element as a prop)

Not every custom prop is evil. Often you'll want to change the underlying HTML element rendered by a single element. And adding a custom prop is the only way to achieve that.

并非每个定制道具都是邪恶的。 通常,您将需要更改由单个元素呈现的基础HTML元素。 并且添加自定义道具是实现这一目标的唯一方法。

A common example is rendering a Button as an <;a>:

一个常见的示例是将Button呈现为< ; a>:

<Button as="a" href="https://google.com">  Go To Google</Button>

Or as another component:

或作为另一个组件:

<Button as={Link} to="/posts">  Posts</Button>

If you're interested on this feature, I recommend you to take a look at ReaKit, a React UI toolkit built with Singel in mind.

如果您对此功能感兴趣,建议您看一下ReaKit ,这是一个考虑到Singel的React UI工具包。

使用Singel CLI验证单个元素 (Validate your single elements using Singel CLI)

Finally, after reading all this, you may have wondered if there is a tool to automatically validate your elements against this pattern. I have developed such a tool, Singel CLI.

最后,在阅读完所有这些内容之后,您可能想知道是否存在一种工具可以根据该模式自动验证您的元素。 我已经开发了Singel CLI这样的工具。

If you want to use it on an ongoing project, I suggest you create a new folder and start putting your singel elements there.

如果要在正在进行的项目中使用它,建议您创建一个新文件夹,然后开始在其中放置singel元素。

If you're using React, you can install singel through npm and run it this way:

如果您使用的是React,则可以通过npm安装singel并以这种方式运行它:

$ npm install --global singel$ singel components/*.js

The output will be similar to this:

输出将类似于以下内容:

Another good way is to install it as a dev dependency in your project and add a script into package.json:

另一种好方法是将其作为开发依赖项安装在项目中,并将脚本添加到package.json

$ npm install --dev singel
{  "scripts": {    "singel": "singel components/*.js"  }}

Then, just run the npm script:

然后,只需运行npm脚本:

$ npm run singel

谢谢您阅读此篇! (Thank you for reading this!)

If you like it and find it useful, here are some things you can do to show your support:

如果您喜欢它并觉得有用,则可以执行以下操作以显示您的支持:

翻译自: https://www.freecodecamp.org/news/introducing-the-single-element-pattern-dfbd2c295c5d/

php 空间类元素引入

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值