快速掌握react_React的五指死亡。 掌握这五个概念,然后掌握React。

快速掌握react

by Sacha Greif

由Sacha Greif

React的五指死亡。 掌握这五个概念,然后掌握React。 (React’s Five Fingers of Death. Master these five concepts, then master React.)

A few years ago, my friend Sean started telling me how this brand new front-end library called React was going to take over the web. At first I dismissed it as just another framework fad. But then I started hearing about React more and more, to the point where I felt like ignoring it just wasn’t an option anymore.

几年前,我的朋友肖恩(Sean)开始告诉我这个叫做React的全新前端库将如何接管网络。 最初,我将其视为另一种框架风尚。 但是后来我开始越来越多地听到关于React的消息,以至于我想忽略它已经不再是一种选择。

Maybe you’re in the same position I was in: you’ve been hearing about React left and right, but actually sitting down and learning it feels like such a chore.

也许您和我所处的位置相同:您曾经听说过左右左右的React,但实际上坐下来学习它感觉就像是一件琐事。

The good news is that you can boil everything you need to know about React down to five key concepts.

好消息是,您可以将关于React所需的所有知识分解为五个关键概念

Now don’t get me wrong, this doesn’t mean I can turn you into a React master instantly. But at least you’ll understand all the major concepts, if you do decide to jump in.

现在不要误会我的意思,这并不意味着我可以立即将您变成React Master。 但是,如果您决定参与其中,那么至少您将了解所有主要概念。

The five key concepts are:

五个关键概念是:

  1. Components

    组件

  2. JSX

    JSX

  3. Props & State

    道具与状态

  4. The Component API

    组件API

  5. Component Types

    组件类型

Before we get started, note that I originally learned React through Wes Bos’s courses, and have included a few affiliate links to them. Whenever possible, I’ve also included links to free resources.

在开始之前,请注意,我最初是通过Wes Bos的课程学习React的,并包括一些与之相关的会员链接。 只要有可能,我都会提供指向免费资源的链接。

Oh, and my friend Sean? He’s since moved on to much more cutting-edge-ier things. After all, React is so 2015.

哦,还有我的朋友肖恩? 从那以后,他开始从事更前沿的事情。 毕竟,React在2015年是如此

概念1:React组件如何工作 (Concept 1: How React components work)

The first thing you need to know about React is that it’s all about components. Your React codebase is basically just one large pile of big components that call smaller components.

关于React,您需要了解的第一件事就是它与组件有关。 您的React代码库基本上只是一大堆称为小组件的大组件。

But what’s a component, you ask? A perfect example of a component is the common <select> HTML element. Not only does it come with its own visual output (the grey box, text label, and downward arrow that make up the element itself) — it also handles its own opening and closing logic.

但是,您要问什么呢? 常见的<sele ct> HTML元素是组件的完美示例。 它不仅具有自己的视觉输出(灰色框,文本标签和构成元素本身的向下箭头),而且还处理自己的打开和关闭逻辑。

Now imagine being able to build your own self-contained custom <select>, with its own style and behavior:

现在想象一下,能够以自己的样式和行为构建自己的自包含自定义<sele ct>:

Well, that’s exactly what React lets you do. A React component is a single object that not only outputs HTML like a traditional template would, but also includes all the code needed to control that output.

好吧,这正是React可以让您做的。 React组件是一个对象,不仅可以像传统模板一样输出HTML,而且还包括控制该输出所需的所有代码。

In practice, the most common way to write React components is as an ES6 class containing a render method that returns HTML. (There’s also a super-secret functional way, but you’ll have to wait until concept #4 to learn about it):

实际上,编写React组件的最常见方法是作为ES6类,其中包含返回HTML的render方法。 (还有一种超级秘密的功能方式,但是您必须等到概念4才能了解它):

class MyComponent extends React.Component {
render() {    return <p>Hello World!<p>;  }
}

概念2:JSX的工作方式 (Concept 2: How JSX works)

As you can see, the component approach means that both HTML and JavaScript code live in the same file. React’s secret weapon to achieve this unholy alliance is the JSX language (where “X” stands for “XML”).

如您所见,组件方法意味着HTML和JavaScript代码都位于同一个文件中。 React实现这种邪恶联盟的秘密武器是JSX语言 (其中“ X”代表“ XML”)。

JSX might seem awkward at first, but you get used to it pretty fast.

JSX乍一看似乎很尴尬,但是您很快就习惯了。

Yes, I know. We’ve all been taught to maintain a strong separation between HTML and JavaScript. But it turns out that relaxing these rules a bit can actually do wonders for your front-end productivity.

是的我知道。 我们都被教导要在HTML和JavaScript之间保持强烈的分离。 但是事实证明,放宽这些规则实际上可以为您的前端生产力带来奇迹。

For example, since you now have the full power of JavaScript at your disposal, here’s how you can display the current date by inserting a snippet of JavaScript in your HTML using {...}:

例如,由于您现在可以使用JavaScript的全部功能,因此可以通过以下方法来显示当前日期,方法是使用{...}在HTML中插入JavaScript片段:

class MyComponent extends React.Component {
render() {    return <p>Today is: {new Date()}</p>;  }
}

This also means that you’ll use plain JavaScript for if statements or loops, rather than some kind of template-specific syntax. JavaScript’s ternary operator comes in especially handy here:

这也意味着您将对if语句或循环使用普通JavaScript,而不是某种特定于模板的语法。 JavaScript的三元运算符在这里特别方便:

class MyComponent extends React.Component {
render() {    return <p>Hello {this.props.someVar ?  'World' : 'Kitty'}</p>;  }
}

And by the way, if you need to brush up on the newest points of JavaScript syntax, I recommend ES6 for Everyone by Wes Bos (if you like videos) or Practical ES6 by Nicolas Bevacqua (if you prefer reading).

顺便说一句,如果您需要重新学习JavaScript语法的最新知识,我建议Wes Bos编写ES6 for Everyone (如果您喜欢视频)或Nicolas Bevacqua编写实用ES6 (如果您喜欢阅读)。

概念3:道具和国家如何运作 (Concept 3: How Props & State work)

Maybe you’ve been wondering where the this.props.someVar variable above is coming from.

也许您一直想知道上面的this.props.someVar变量来自何处。

If you’ve ever written a line of HTML, you’re probably familiar with HTML attributes like the <;a> tag’s href. In React, attributes are known as props (short for “properties”). Props are how components talk to each other.

如果您曾经编写过一行HTML,那么您可能已经熟悉HTML属性,例如< ; a> tag' s href。 在React中,属性被称为 props(“属性”的缩写)。 道具是组件之间如何对话的方式。

class ParentComponent extends React.Component {
render() {    return <ChildComponent message="Hello World"/>;  }
}
class ChildComponent extends React.Component {
render() {    return <p>And then I said, “{this.props.message}”</p>;  }
}

Because of this, React’s data flow is unidirectional: data can only go from parent components to their children, not the other way around.

因此,React的数据流是单向的 :数据只能从父组件传递到子组件,而不能相反。

Sometimes though, a component needs to react to data that doesn’t come from a parent component (such as user input for example). And this is where the state comes in.

但是有时候,某个组件需要对不是来自父组件的数据做出React(例如,用户输入)。 这就是国家的来历。

A good metaphor to understand the difference between props and state would be the Etch-A-Sketch. Unlike things like the body color and dial position of the Etch-A-Sketch tablet (props), the drawing itself (state) is not an inherent property of the Etch-A-Sketch. It’s just the temporary result of user input.

理解道具与状态之间差异的一个很好的隐喻是蚀刻蚀刻。 与诸如Etch-A-Sketch平板电脑( 道具 )的车身颜色和刻度盘位置不同的是,图形本身( 状态 )不是Etch-A-Sketch的固有属性。 这只是用户输入的临时结果。

Note that a component’s state can also be passed on to its own children as a prop. You can think of this as a big river flowing downhill, with the router, data layer, and various components each adding their own little stream of data to form the main app state.

注意,组件的状态也可以作为prop传递给自己的子级。 您可以认为这是一条下坡的大河,路由器,数据层和各种组件各自添加自己的少量数据流以形成主要应用程序状态。

Inside a component, state is managed using the setState function, which is often called inside an event handler:

在组件内部,使用setState函数管理状态,该函数通常在事件处理程序内部调用:

class MyComponent extends React.Component {
handleClick = (e) => {    this.setState({clicked: true});  }
render() {    return <a href="#" onClick={this.handleClick}>Click me</a>;  }
}

In practice, the vast majority of data in a React app will be a prop. It’s only when you need to accept user input that you’ll use state to handle the change.

实际上,React应用程序中的绝大多数数据都是prop 。 只有当您需要接受用户输入时,才可以使用状态来处理更改。

Note that we’re using a fat arrow here to take care of binding the handleClick handler. You can learn more about this technique here.

请注意,这里我们使用粗箭头来绑定handleClick处理程序。 您可以在此处了解有关此技术的更多信息

概念4:组件API的工作方式 (Concept 4: How the Component API works)

We’ve already mentioned render and setState, which are both part of a small set of component API methods. Another useful one is the constructor, which you can use to initialize your state and bind methods.

我们已经提到过rendersetState ,它们都是一小部分组件API方法的一部分。 另一个有用的constructorconstructor ,可用于初始化状态和绑定方法

Apart from these three functions, React also provides a set of callbacks triggered at various points during the component’s lifecycle (before loading, after loading, after unmounting, and so on). Unless you’re doing some advanced React voodoo, you’ll probably almost never need to worry about these.

除了这三个功能,React还提供了一组在组件生命周期中的各个点(加载之前,加载之后,卸载之后等等)触发的回调。 除非您正在使用高级React伏都教,否则您几乎永远不必担心这些。

If this section seems short, it’s because learning React is actually much more about mastering programming and architectural concepts rather than learning a set of boring API methods. This is what makes it so refreshing!

如果本节很短,那是因为学习React实际上更多是关于掌握编程和体系结构概念,而不是学习一套枯燥的API方法。 这就是让它如此清新的原因!

概念5:组件类型如何工作 (Concept 5: How Component Types work)

We’ve seen how to use classes to define a component:

我们已经看到了如何使用类来定义组件:

class MyComponent extends React.Component {
render() {    return <p>Hello World!<p>;  }
}

And we’ve also talked about the component methods supported by these classes. Now forget all about them! More and more, people are writing React components as functional components.

我们还讨论了这些类支持的组件方法。 现在,忘记它们! 人们越来越多地将React组件编写为功能组件

A functional component is a function that takes a props object as argument, and returns a bunch of HTML. Almost like a traditional template, with the key difference that you can still use whatever JavaScript code you need inside that function:

功能组件是将props对象作为参数并返回一堆HTML的函数。 几乎就像传统模板一样,主要区别在于您仍可以在该函数内使用所需的任何JavaScript代码:

const myComponent = props => {
return <p>Hello {props.name}! Today is {new Date()}.</p>
}

The consequence of using the functional component syntax is that you lose access to the component methods we just talked about. But it turns out that in practice that’s perfectly fine, since the vast majority of your components probably won’t need them.

使用功能性组件语法的结果是,您将无法访问我们刚刚谈到的组件方法。 但是事实证明,实际上这是完全可以的,因为您的绝大多数组件可能都不需要它们。

By the way, one of these methods is setState, and this means functional components cannot have state. For that reason they’re often referred to as stateless functional components.

顺便说一下,这些方法之一是setState ,这意味着功能组件不能具有状态。 因此,它们通常被称为无状态功能组件。

Since functional components require much less boilerplate code, it makes sense to use them whenever possible. For this reason, most React apps contain a healthy mix of both syntaxes.

由于功能组件所需的样板代码少得多,因此尽可能使用它们是有意义的。 因此,大多数React应用程序都包含两种语法的健康组合。

Note that there’s also a third, legacy syntax using the createClass function. But anybody using it should be shamed and called names for daring to still be using coding patterns from 18 months ago:

请注意,还有第三种使用createClass函数的旧式语法。 但是任何使用它的人都应该感到羞耻并称呼他们为敢于继续使用18个月前的编码模式的名字:

var Greeting = React.createClass({     render: function() {         return <h1>Hello, {this.props.name}</h1>;     }
});

概念6:组件角色如何工作 (Concept 6: How Component Roles work)

OK, I lied. There are actually six things, not five. But what can I say, the movie isn’t called “Six Fingers Of Death.” Although now that I think about it, that sounds like it’d be a pretty cool movie, probably involving some kind of alien kung-fu master seeking revenge.

好我撒谎了 实际上有六件事,而不是五件事。 但是我能说的是,这部电影没有被称为“死亡的六个手指”。 尽管现在我已经考虑过了,但这听起来像是一部很酷的电影,可能涉及某种寻求报仇的外星功夫大师。

But back to the topic at hand. Now come the boring architectural concepts I was talking about. So if none of this makes sense feel free to come back once you’ve had a chance to play with React some more.

但是回到手头的话题。 现在是我正在谈论的无聊的建筑概念。 因此,一旦您有机会再与React一起玩,如果这些都不是让您随意回来的话。

After using React for a while, people started seeing two distinct “flavors” of code appear in their components: one flavor was concerned with UI logic such as showing and hiding thing. And the other was all about data logic, such as loading data from your server.

在使用React一段时间后,人们开始看到两种不同的代码“味道”出现在其组件中:一种味道与UI逻辑有关,例如显示和隐藏事物。 另一个与数据逻辑有关,例如从服务器加载数据。

This led to the distinction between container and presentational components (also sometimes known as “smart” and “dumb” components). Container components should handle your data, but — and this is the important part — not your UI. Presentational components are just the opposite.

这导致了容器组件和表示组件(有时也称为“ 智能 ”和“ ”组件)之间的区别。 容器组件应该处理您的数据,但是-这是重要的部分- 不是您的UI。 表示组件恰好相反。

In other words, in the classic to-do list example, one component will load the data, and then pass that data on to a different component that will be in charge of outputting the actual HTML markup and handling local state changes.

换句话说,在经典的待办事项清单示例中,一个组件将加载数据,然后将数据传递到另一个组件,该组件将负责输出实际HTML标记并处理本地状态更改。

This is very similar to the view/controller pattern you might be familiar with from your back-end developer days. (’member Rails? ’member Django?)

这与您在后端开发人员时代可能熟悉的视图/控制器模式非常相似。 ( “成员Rails?”成员Django? )

The container/presentational distinction was popularized in this blog post by Dan Abramov (the creator of Redux), and I recommend checking it out if you want to dig deeper.

容器/表示形式的区别在此博客中由Red Aux的创建者Dan Abramov推广,如果您想更深入地研究,我建议您检查一下。

高阶组件 (Higher-Order Components)

Before we wrap things up, we should talk a bit about a type of container components known as higher-order components (often shortened as HoCs).

在总结之前,我们应该先谈谈一种容器组件的类型,称为高阶组件 (通常简称为HoC)。

A HoC is a component that you can wrap around another component to pass it special props, and it’s typically created using a higher-order component factory function. Note that people commonly refer to the function itself as a “HoC”, which might not be 100% correct technically, but isn’t a big deal in practice.

HoC是一个组件,您可以将其包裹在另一个组件上以传递特殊的道具,它通常是使用高阶组件工厂函数创建的 。 请注意,人们通常将功能本身称为“ HoC ”,从技术上讲可能不是100%正确的,但实际上并不重要。

As an example, calling React Router’s withRouter factory function on <MyComponent>will wrap it in a new<withRouter(MyComponent)/> component that passes the Router prop to the afore-mentioned &lt;MyComponent>.

作为示例,调用阵营路由器withRouter工厂功能上<MyCompone NT>将包装在a new<withRouter(MyCom Ponent(波纳恩特))/>部件,其passe S上的路由器丙到AFOR e-mentioned & LT; MyComponent的>。

You can think of a HoC function as a golf caddie that follows their golfer around and hands them the club they need it. By themselves, the caddie can’t actually do anything with the golf clubs. They’re just there to give the golfer access to more tools.

您可以将HoC功能看作是一个高尔夫球童车,它跟随着高尔夫球手,并将他们需要的球杆交给他们。 球童自己实际上不能对高尔夫球杆任何事情。 他们只是在那里,使高尔夫球手可以使用更多工具。

HoCs are a very powerful concept. For example, the Recompose library even lets you handle state changes through HoCs. In other words, you can now manage state without having to involve any ES6 class-based components.

HoC是一个非常强大的概念。 例如, 重新构图库甚至可以让你处理过肝卵圆细胞状态的变化。 换句话说,您现在可以管理状态,而不必涉及任何基于ES6类的组件。

With HoC composition becoming so common, it seems like React might be moving away from the ES6 class syntax and more towards a purely functional approach. Interesting times!

随着HoC组合变得如此普遍,React似乎正在从ES6类语法转移到更纯粹的功能方法。 有趣的时代!

回顾 (Recap)

So let’s recap what we’ve just learned:

因此,让我们回顾一下我们刚刚学到的东西:

  • A React codebase is made up of components.

    React代码库由组件组成。
  • These components are written using JSX.

    这些组件是使用JSX编写的。
  • Data flows from parent to children, except when it comes to state, which originates inside a component.

    数据从父级流到子级,除非涉及到state ,它来自组件内部。

  • Components possess a small set of lifecycle and utility methods.

    组件拥有少量的生命周期和实用方法。
  • Components can also be written as pure functions.

    组件也可以写为纯函数。
  • You should keep data logic and UI logic in separate components.

    您应该将数据逻辑和UI逻辑放在单独的组件中。
  • Higher-order components are a common pattern for giving a component access to new tools.

    高阶组件是使组件可以使用新工具的常见模式。

Believe it or not, we’ve just covered 90% of the knowledge used by a React developer on a daily basis. No matter how abstract or obscure the pattern, everything in React can always be boiled down to functions and props.

信不信由你,我们已经覆盖了React开发人员每天使用的90%的知识。 无论模式多么抽象或模糊,React中的所有内容都可以归结为功能和道具。

Once you truly understand this, React will stop being scary. You’ll be able to see patterns in the code, understand new codebases at a glance, and only then will you be able to proudly proclaim:

一旦您真正理解了这一点,React将不再令人恐惧。 您将能够看到代码中的模式,一目了然地了解新的代码库,然后您才能自豪地宣称:

“Pfff! React is so 2015!”

“ PFFF! React 真是 2015年!”

走得更远 (Going Further)

If I’ve managed to convince you that React isn’t so bad, you might want to take a stab at learning it properly. If so, I can’t recommend the React for Beginners video course enough. It’s how I learned React myself, and it’s actually just been updated to cover all the cool new stuff like functional stateless components:

如果我设法说服了React并没有那么糟糕,那么您可能想尝试一下适当地学习它。 如果是这样,我就不能推荐足够的“ 初学者React”视频课程。 这是我自己学习React的方式,实际上它已经进行了更新,以涵盖所有很酷的新内容,例如功能性无状态组件:

If you don’t want your hard-earned dollars to finance the nefarious React lobby (I heard Dan Abramov is onto his third yacht), you can also learn for free by checking out this huge list of React resources.

如果您不想用辛苦赚来的钱来资助邪恶的React大厅(我听说Dan Abramov登上了他的第三艘游艇),那么您也可以免费查看这个庞大的React资源列表,免费学习。

And if you need to put all this newly-acquired knowledge in practice by contributing to a cool React open-source project, check out Telescope Nova. It’s the easiest way to quickly create a full-stack React + GraphQL app, complete with user accounts, forms, and data loading out of the box. And did I mention we’re looking for contributors?

并且,如果您需要通过参与一个很棒的React开源项目来将所有这些新获得的知识付诸实践,请查看Telescope Nova 。 这是快速创建全栈式React + GraphQL应用程序的最简单方法,其中包括开箱即用的用户帐户,表单和数据加载。 我是否提到我们正在寻找贡献者?

Finally, if you’ve enjoyed this article, please share it and recommend it (that little green heart just below). And please let me know on Twitter what you’d like me to write about next!

最后,如果您喜欢本文,请分享并推荐(下面是那颗绿色的小心脏)。 并请让我在Twitter上知道您接下来要写些什么!

翻译自: https://www.freecodecamp.org/news/the-5-things-you-need-to-know-to-understand-react-a1dbd5d114a3/

快速掌握react

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值