react构建

by Scott Domes

由斯科特·多姆斯(Scott Domes)

您应该了解的有关React的一切:开始构建所需的基础知识 (Everything You Should Know About React: The Basics You Need to Start Building)

Are you curious about React and haven’t had the chance to learn it? Or maybe you’ve tried tutorials in the past, but struggled to master the core concepts? Or maybe you’ve learned the basics, but want to consolidate your knowledge? Either way, this article is for you.

您是否对React感到好奇,还没有机会学习它? 或者,也许您过去曾经尝试过教程,但却难以掌握核心概念? 或者,也许您已经学习了基础知识,但想巩固您的知识? 无论哪种方式,本文都适合您。

We’re going to build a simple React music player, layering on new React concepts as we go.

我们将构建一个简单的React音乐播放器,并在开发过程中以新的React概念为基础。

Here’s what we’ll cover:

这是我们要介绍的内容:

  • What is a React component?什么是React组件?
  • ReactDOM renderingReactDOM渲染
  • Class vs functional components类与功能组件
  • JSXJSX
  • State州
  • Event handling事件处理
  • Asynchronous setState异步setState
  • Props道具
  • Refs参考

That’s just about everything you need to build and maintain a React application. But we’re going to introduce it piece-by-piece.

这就是构建和维护React应用程序所需的一切。 但是,我们将逐个介绍它。

建立 (Setup)

Here’s the situation: a small start-up has reached out to you for your help. They’ve created a page for users to upload music and have it visualized in glowing colour. But they need you to do the hard part—AKA to make it work.

情况就是这样:一家小型创业公司已经向您寻求帮助。 他们创建了一个页面供用户上传音乐,并以发光的颜色对其进行可视化。 但是他们需要您尽力而为-使其工作。

To get going, make a new project directory and add the following three files.

首先,创建一个新的项目目录并添加以下三个文件 。

Make sure you’re using an up-to-date version of Chrome with this tutorial, otherwise the animations in the code above won’t work.

请确保您在本教程中使用的是最新版的Chrome ,否则上面代码中的动画将不起作用。

Thanks to Steven Fabre for the play button CSS and Justin Windle for visualization code (you can view the original here).

感谢Steven Fabre提供CSS播放按钮,以及Justin Windle的可视化代码( 您可以在此处查看原始内容 )。

Open up index.html in both a code editor and your browser, and let’s get started!

在代码编辑器和浏览器中打开index.html ,让我们开始吧!

什么是React? (What is React?)

React is a way to build user interfaces. It is only concerned with what you see on the front-end. React makes user interfaces very easy to build by cutting each page into pieces. We call these pieces components.

React是一种构建用户界面的方法。 它只与您在前端看到的内容有关。 通过将每个页面分成几部分,React使用户界面的构建非常容易。 我们称这些部件为组件。

Here is an example of cutting a page into components:

这是将页面切成组件的示例:

Each section highlighted above is considered a component. But what does this mean for a developer?

上面突出显示的每个部分都被视为一个组件。 但这对开发人员意味着什么?

什么是React组件? (What is a React Component?)

A React component is a bit of code that represents a piece of the page. Each component is a JavaScript function that returns a piece of code that represents a piece of a web page.

React组件是代表一部分页面的一些代码。 每个组件都是一个JavaScript函数,该函数返回代表网页的一段代码。

To build a page, we call these functions in a certain order, put together the result, and show it to the user.

为了构建页面,我们以一定的顺序调用这些函数,将结果放在一起,并显示给用户。

Let’s write a component inside the <script> tag in index.html with the type of “text/babel”:

让我们写内部的部件的<scri PT>吨ag in inde x.html机智h th ÈTY pe of “text/巴别”:

<script type="text/babel">  function OurFirstComponent() {    return (      // Code that represents the UI element goes here    );  }</script>

When we call the OurFirstcomponent() function, we will get back a piece of the page.

当我们调用OurFirstcomponent()函数时,我们将返回页面的一部分。

You can also write functions like this:

您还可以编写如下函数:

const OurFirstComponent = () => {  return (    // Stuff to make this component goes here  );}

React uses a language called JSX that looks like HTML but works inside JavaScript, which HTML usually doesn’t do.

React使用一种叫做JSX的语言,它看起来像HTML,但是可以在JavaScript内运行,而HTML通常是不支持的。

You can add plain HTML to this section to make it appear on the UI:

您可以将纯HTML添加到此部分,以使其出现在UI中:

<script type="text/babel">  function OurFirstComponent() {    return (      <h1>Hello, I am a React Component!</h1>    );  }</script>

When we call the OurFirstComponent() function, we get back a bit of JSX. We can use something called ReactDOM to put it on the page.

当我们调用OurFirstComponent()函数时,我们会得到一些JSX。 我们可以使用称为ReactDOM的东西将其放在页面上。

<script type="text/babel">  function OurFirstComponent() {    return (      <h1>Hello, I am a React Component!</h1>    );  }
const placeWeWantToPutComponent = document.getElementById('hook');  ReactDOM.render(OurFirstComponent(), placeWeWantToPutComponent);</script>

Now our <h1> tag will be put inside the element with the ID of hook. It should look like this when you refresh your browser:

现在,我们的< h1>标记将被放置在具有钩子ID of的元素内。 刷新浏览器时,它应如下所示:

We can also write our component in JSX like so:

我们也可以像这样在JSX中编写组件:

ReactDOM.render(<OurFirstComponent />, placeWeWantToPutComponent);

This is standard — invoke your components like you are writing HTML.

这是标准的-就像编写HTML一样调用组件。

将组件放在一起 (Putting Components Together)

We can put React components inside other components.

我们可以将React组件放入其他组件中。

<script type="text/babel">  function OurFirstComponent() {    return (      <h1>I am the child!</h1>    );  }
function Container() {    return (      <div>        <h1>I am the parent!</h1>        <OurFirstComponent />      </div>    );  }
const placeWeWantToPutComponent = document.getElementById('hook');  ReactDOM.render(<Container />, placeWeWantToPutComponent);</script>

This is how we build our page out of pieces of React — by nesting components inside of each other.

这就是我们通过将组件嵌套在彼此之间,从而利用React片段构建页面的方式。

类组件 (Class Components)

So far, we’ve been writing components as functions. These are called functional components.

到目前为止,我们一直在将组件编写为函数。 这些称为功能组件。

But you can write components another way, as JavaScript classes. These are called class components.

但是您可以使用另一种方式编写组件,例如JavaScript类。 这些称为类组件。

class Container extends React.Component {  render() {    return (      <div>        <h1>I am the parent!</h1>        <OurFirstComponent />      </div>    );  }}
const placeWeWantToPutComponent = document.getElementById('hook');ReactDOM.render(<Container />, placeWeWantToPutComponent);

Class components must have a function called render(). The render function returns the JSX of the component. They can be used the same way as functional components, like this:<AClassComponent />.

类组件必须具有一个称为render()的函数 render函数返回组件的JSX。 它们可以与功能组件相同的方式使用,如下所示: <AClassComponent />。

You should use functional components over class components because they’re easier to read, unless you need component state (more on that soon).

您应该在类组件上使用功能组件,因为它们更易于阅读,除非您需要组件状态 (稍后会介绍更多)。

JSX中JavaScript (JavaScript in JSX)

You can put JavaScript variables inside of your JSX like this:

您可以像这样将JavaScript变量放入JSX:

class Container extends React.Component {  render() {    const greeting = 'I am a string!';    return (      <div>        <h1>{ greeting }</h1>        <OurFirstComponent />      </div>    );  }}

Now the ‘I am a string!’ will be inside the h1.

现在,“我是弦乐!” 将在h1

You can also do more difficult stuff, like call a function:

您还可以执行更困难的工作,例如调用函数:

class Container extends React.Component {  render() {    const addNumbers = (num1, num2) => {      return num1 + num2;    };    return (      <div>        <h1>The sum is: { addNumbers(1, 2) }</h1>        <OurFirstComponent />      </div>    );  }}

JSX陷阱 (JSX Gotchas)

Rename OurFirstComponent() to PlayButton. We want it to return the following:

OurFirstComponent()重命名为PlayButton 。 我们希望它返回以下内容:

<a href="#" title="Play video" class="play" />

But there’s a problem: class is a keyword in JavaScript, so we can’t use it. So how do we give our <;a> a class of play?

但是有一个问题: class是JavaScript中的关键字,因此我们不能使用它。 那么,如何才能让我们的< ;一>一CLA ss o ˚F玩吗?

Use a property called className instead:

使用名为className的属性代替:

<script type="text/babel">  function PlayButton() {    return <a href="#" title="Play video" className="play" />;  }
class Container extends React.Component {    render() {      return (        <div>          <PlayButton />        </div>      );    }  }
const placeWeWantToPutComponent = document.getElementById('hook');  ReactDOM.render(<Container />, placeWeWantToPutComponent);</script>

该组件在做什么? (What Is This Component Doing?)

Class components can store information about their current situation. This information is called state, which is stored in a JavaScript object.

类组件可以存储有关其当前情况的信息。 此信息称为state ,它存储在JavaScript对象中。

In the code below, we have an object representing our components state. It has a key of isMusicPlaying which has a value of false. This object is assigned to this.state in the constructor method, which is called when the class is first used.

在下面的代码中,我们有一个表示组件状态的对象。 它具有isMusicPlaying key ,其value false 。 该对象在constructor方法中分配给this.state ,该方法在首次使用该类时被调用。

class Container extends React.Component {  constructor(props) {    super(props);    this.state = { isMusicPlaying: false };  }    render() {    return (      <div>        <PlayButton />      </div>    );  }}

A constructor method of a React component always needs to call super(props) before anything else.

React组件的constructor方法始终需要先调用super(props)

Okay, so what do we do with state? Why does it exist?

好的,我们该如何处理state ? 为什么存在?

根据状态更改React组件 (Changing Our React Component Based On State)

State is way to update our UI based on events.

状态是基于事件更新我们的UI的方法。

In this tutorial, we will use state to change the play button from paused to playing based on the user clicking the play button.

在本教程中,我们将使用状态来改变播放按钮从暂停 根据用户点击播放按钮。

When the user clicks on the button, the state will update, which will then update the UI.

当用户单击按钮时,状态将更新,然后状态将更新UI。

Here’s how we get started. We can look at the component state with this.state. In the following code, we look at the state and use it to decide what text to present to the user.

这是我们的入门方法。 我们可以使用this.state查看组件状态。 在下面的代码中,我们查看状态并使用它来决定向用户呈现什么文本。

class Container extends React.Component {  constructor(props) {    super(props);    this.state = { isMusicPlaying: false };  }
render() {    const status = this.state.isMusicPlaying ? 'Playing' : 'Not playing';    return (      <div>        <h1>{ status }</h1>        <PlayButton />      </div>    );  }}

In the render function, this is always referring to the component it is within.

在render函数中, this始终是指其所在的组件。

But that’s not very useful unless we have a way to change this.state.isMusicPlaying.

但这不是很有用,除非我们有办法更改this.state.isMusicPlaying

当东西发生在我们的组件上 (When Stuff Happens to Our Component)

The user can interact with our components by clicking on the play button. We want to react (ha… ha…) to those events.

用户可以通过单击播放按钮与我们的组件进行交互。 我们想对这些事件做出React(哈……哈……)。

We do that through functions that take care of events. We call these event handlers.

我们通过负责事件的功能来做到这一点。 我们称这些事件处理程序

class Container extends React.Component {  constructor(props) {    super(props);    this.state = { isMusicPlaying: false };  }
handleClick(event) {    // Do something about the click  };
render() {    let status = this.state.isMusicPlaying     ? 'Playing :)'     : 'Not playing :(';    return (      <div>        <h1 onClick={this.handleClick.bind(this)}>{ status }</h1>        <PlayButton />      </div>    );  }}

When the user clicks on the h1, our component will make the handleClick function run. The function gets the event object as the argument, which means it can use it if it wanted to.

当用户单击h1 ,我们的组件将使handleClick函数运行。 该函数将事件对象作为参数,这意味着它可以在需要时使用它。

We use the .bind method on handleClick to make sure this refers to the whole component, rather than just the h1.

我们在handleClick上使用.bind方法,以确保this引用的是整个组件,而不仅仅是h1

该组件应该做什么 (What This Component Should Be Doing)

When we change the state of our component, it will call the render function again.

当我们更改组件的状态时,它将再次调用render函数。

We can change state with this.setState(), if we give it a new object representing the new state.

如果我们给它一个表示新状态的新对象,则可以使用this.setState()更改状态。

Our component on the page will always represent its current state. React does that for us.

页面上的组件将始终代表其当前状态。 React为我们做到了。

handleClick() {    if (this.state.isMusicPlaying) {      this.setState({ isMusicPlaying: false });    } else {      this.setState({ isMusicPlaying: true });    }  };

But clicking an h1 isn’t as good as clicking our actual play button. Let’s make that work.

但是单击h1不如单击我们的实际播放按钮那样好。 让我们开始吧。

组件之间的对话 (Talking Between Components)

Your components can talk to each other. Let’s try it.

您的组件可以互相通信。 让我们尝试一下。

We can tell PlayButton whether or not the music is playing using something called props. Props are information shared from a parent component to a child component.

我们可以使用props来告诉PlayButton音乐是否正在播放。 道具是从父组件共享到子组件的信息。

Props in JSX look the same as HTML properties.

JSX中的道具看起来与HTML属性相同。

We give PlayButton a prop called isMusicPlaying, which is the same as the isMusicPlaying in this.state.

我们给PlayButton一个道具叫isMusicPlaying ,这是一样的isMusicPlayingthis.state

class Container extends React.Component {  constructor(props) {    super(props);    this.state = { isMusicPlaying: false };  }
handleClick() {    if (this.state.isMusicPlaying) {      this.setState({ isMusicPlaying: false });    } else {      this.setState({ isMusicPlaying: true });    }  };
render() {    return (      <div>        <PlayButton isMusicPlaying={this.state.isMusicPlaying} />      </div>    );  }}

When the state of Container changes, PlayButton prop will change too, and the PlayButton function will be called again. That means our component will update on the screen.

Container的状态更改时, PlayButton也将更改,并且PlayButton函数将再次被调用。 这意味着我们的组件将在屏幕上更新。

Inside PlayButton, we can react to the change, because PlayButton gets the props as an argument:

PlayButton ,我们可以对更改做出React,因为PlayButton将props作为参数:

function PlayButton(props) {  const className = props.isMusicPlaying ? 'play active' : 'play';  return <a href="#" title="Play video" className={className} />;}

If we change our state to this.state = { isMusicPlaying: true }; and reload the page, you should see the pause button:

如果我们将状态更改为this.state = { isMusicPlaying: true }; 并重新加载页面,您应该看到“暂停”按钮:

活动作为道具 (Events as Props)

Your props don’t have to be just information. They can be functions.

您的道具不必仅仅是信息。 它们可以是函数。

function PlayButton(props) {  const className = props.isMusicPlaying ? 'play active' : 'play';  return <;a onClick={props.onClick} href="#" title="Play video" className={className} />;}
class Container extends React.Component {  constructor(props) {    super(props);    this.state = { isMusicPlaying: false };  }
handleClick() {    if (this.state.isMusicPlaying) {      this.setState({ isMusicPlaying: false });    } else {      this.setState({ isMusicPlaying: true });    }  };
render() {    return (      <div>        <PlayButton           onClick={this.handleClick.bind(this)}           isMusicPlaying={this.state.isMusicPlaying}         />      </div>    );  }}

Now, when we click on the PlayButton, it’ll change the state of Container, which will change the props of PlayButton, which will cause it to update on the page.

现在,当我们单击PlayButton ,它将更改Container的状态,这将更改PlayButtonprops ,这将使其在页面上更新。

关于setState的坏事 (The Bad Thing About setState)

setState is bad because it doesn’t do stuff right away. React waits a bit to see if there are more changes to make, then it does the state changes.

setState不好,因为它不会立即做任何事情。 React稍等一下,看看是否还有更多更改要进行,然后它进行状态更改。

That means you don’t know for sure what your state will be when you call setState.

这意味着您不确定调用setState时的状态。

So you shouldn’t do this:

因此,您不应该这样做:

handleClick() {  this.setState({ isMusicPlaying: !this.state.isMusicPlaying });};

If you are changing your state based on the old state, you need to do things differently.

如果您要根据旧状态更改状态,则需要做不同的事情。

You need to give setState a function, not an object. This function gets the old state as an argument, and returns an object that is the new state.

您需要给setState一个函数,而不是一个对象。 此函数将旧状态作为参数,并返回一个新状态的对象。

It looks like this:

看起来像这样:

handleClick() {  this.setState(prevState => {    return {       isMusicPlaying: !prevState.isMusicPlaying       };  });};

It is more difficult, but only needed when you are using the old state to make the new state. If not, you can just give setState an object.

这比较困难,但是只有在使用旧状态创建新状态时才需要。 如果没有,您可以给setState一个对象。

什么是裁判? (What Are Refs?)

Let’s make some music happen.

让我们做些音乐吧。

First, we add an <audio> tag:

首先,我们添加一个<aud io>标签:

class Container extends React.Component {  constructor(props) {    super(props);    this.state = { isMusicPlaying: false };  }
handleClick() {    this.setState(prevState => {      return {         isMusicPlaying: !prevState.isMusicPlaying         };    });  };
render() {    return (      <div>        <PlayButton           onClick={this.handleClick.bind(this)}           isMusicPlaying={this.state.isMusicPlaying}         />        <audio id="audio" />      </div>    );  }}

We need a way to get that <audio> tag and call either play() or pause() on it. We could do it with document.getElementById('audio').play() but there’s a better React way.

我们需要一种方法来获取<aud IO>标签和呼叫E ither播放() or p上澳洲英语()。 我们可以with document.getElementById('audio').做到这一点with document.getElementById('audio'). play()但有更好的React方法。

We give it a prop called ref, which gets called with the <audio> element as the first argument. It takes that &lt;audio> element and assigns it to this.audio.

我们给它提供了一个名为ref的道具,该道具以<aud io>元素作为第一个参数被调用。 它that & lt; audio>元素并将其作为this.audio的signs it t

<audio id="audio" ref={(audioTag) => { this.audio = audioTag }} />

This function will be called every time the Container renders, which means this.audio will always be up to date, and equal the <audio> tag.

每次Container渲染时都会调用此函数,这意味着this.audio将始终是最新的,并且等于<aud io>标签。

We then can play and pause the music:

然后,我们可以播放和暂停音乐:

handleClick() {  if (this.state.isMusicPlaying) {    this.audio.pause();  } else {    this.audio.play();  }  this.setState(prevState => {    return {       isMusicPlaying: !prevState.isMusicPlaying       };  });};

Upload a music file (preferably an mp3 file) using the Choose files button and hit play, and watch it go!

使用“ Choose files按钮上传音乐文件(最好是mp3文件)并点击播放,然后观看吧!

移出Index.html (Moving Outside of Index.html)

As you might have guessed, our React shouldn’t live forever inside a <script>tag.

您可能已经猜到了,我们的React不应永远存在于<scri pt>标签中。

React takes a lot of build configuration. Fortunately, tools like Create React App take care of all that for you.

React需要大量的构建配置。 幸运的是,诸如Create React App之类的工具可以为您完成所有工作。

Install it to create your own React project. Follow their brief tutorial and start editing the JavaScript inside the src directory, applying all the React knowledge you learned here!

安装它以创建自己的React项目。 遵循他们的简短教程,并开始应用src目录中的所有React知识来编辑src目录中JavaScript!

恭喜你! (Congratulations!)

You can now make React things.

您现在可以制作React东西了。

Next, check out a couple of articles for more information. One is about React best practices, the other about a useful part of React called lifecycle methods.

接下来,查看几篇文章以获取更多信息。 一个是关于React最佳实践的 ,另一个是关于React有用部分的生命周期方法

If you learned something from this article, please click those clappin’ hands, and share it with your friends.

如果您从本文中学到了一些知识,请单击那些拍手的手,并将其分享给您的朋友。

You can also follow me on Medium and Twitter.

您也可以在Medium和Twitter上关注我。

翻译自: https://www.freecodecamp.org/news/everything-you-need-to-know-about-react-eaedf53238c4/

react构建

react构建_您应该了解的有关React的一切:开始构建所需的基础知识相关推荐

  1. angular 模块构建_如何通过11个简单的步骤从头开始构建Angular 8应用

    angular 模块构建 Angular is one of the three most popular frameworks for front-end development, alongsid ...

  2. vue nodejs 构建_如何使用nodejs后端打字稿版本开发和构建vue js应用

    vue nodejs 构建 There are so many ways we can build Vue.js apps and ship for production. One way is to ...

  3. ejb构建_如何使用单例EJB,Ehcache和MBean构建和清除参考数据缓存

    ejb构建 在本文中,我将介绍如何使用单例EJB和Ehcache在Java EE中构建简单的参考数据缓存. 高速缓存将在给定的时间段后重置自身,并且可以通过调用REST端点或MBean方法" ...

  4. react钩子_使用Web动画API和React钩子创建高性能动画

    react钩子 以React 挂钩方式使用Web Animations API (又名WAAPI). 让我们在现代世界中创建高性能,灵活和可操作的网络动画. 希望你们

  5. web自动化构建_通过在真实设备上进行自动测试来构建更好的Web

    web自动化构建 This article was originally published on Medium. 本文最初发表在Medium上 . My work is entirely dedic ...

  6. daas 数据即服务_什么是云计算?云的基本特征;云服务模型;--IT基础知识系列...

    美国商务部下设的美国国家标准与技术研究院 (NIST) 在其特刊出版物 800-145 中对云计算 的定义如下: "云计算是一种模型,支持通过网络方便地按需访问由可配置的计算资源(例如网络. ...

  7. 乖离率背离公式_乖离率多少才合理 BIAS指标计算公式-BIAS-技术指标-股票入门基础知识学习网...

    对于炒股的人来说肯定是要了解不同指标的含义和计算公式等等的基本解析了,乖离率(BIAS),又称偏离率,简称Y值,是通过计算市场指数或收盘价与某条移动平均线之间的差距百分比,以反映一定时期内价格与其MA ...

  8. 前端项目结构构建_如何通过构建项目成为更好的前端开发人员(包括想法)

    前端项目结构构建 If you want to fast-track your growth as a front-end developer, nothing beats doing real de ...

  9. 构建一个react项目_您想要了解更多有关React的内容吗? 让我们构建一个游戏,然后玩。...

    构建一个react项目 by Samer Buna 通过Samer Buna 您想要了解更多有关React的内容吗? 让我们构建一个游戏,然后玩. (Do you want to learn more ...

最新文章

  1. 下午花一小时整理的JVM运行时方法区
  2. python画图完整代码-Python科学画图代码分享
  3. 中国在两年内赶超美国AI?李开复:不一定
  4. PE结构延迟加载导入表
  5. spark stage 划分 源码
  6. 文字超过省略_纯CSS实现“文本溢出截断省略”的几种方法
  7. iOS逆向之自动化重签名
  8. Fission for Mac(简易音频编辑软件)附注册码 v2.4.5激活版
  9. R语言教程(1)——基础知识
  10. 【总结】有三AI所有原创人脸相关的学习资料汇总(2022年12月)
  11. 中国互联网二十年回忆
  12. 如何提升自己的宣传效果?从这两个点开始
  13. 零售航母沃尔玛公布业绩:喜忧参半
  14. 导致我们形不成「自律」的「罪魁祸首」
  15. 实现自动WiFi连接
  16. 华为手机计算机的隐藏游戏,怎样把华为手机游戏隐藏起来 | 手游网游页游攻略大全...
  17. css设置 备用 background背景图
  18. 经纬度度与度分格式转化
  19. 2018-12-6【训练日记】
  20. 不生病不算健康,健康的人都有三个特点,看看你占了几点?

热门文章

  1. MMKV集成与原理,薪资翻倍
  2. 最强Android教程!2021年Android面经分享,大厂面经合集
  3. gdb调试的基本使用
  4. virtualbox 使用
  5. SpringBoot中各配置文件的优先级及加载顺序
  6. Spring-Security 自定义Filter完成验证码校验
  7. [转]DevExpress GridControl 关于使用CardView的一点小结
  8. WPF疑难杂症之二(全屏幕窗口)
  9. knife4j是为Java MVC框架集成Swagger生成Api文档的增强解决方案
  10. 基于easyui开发Web版Activiti流程定制器详解(一)——目录结构