Translation | "JavaScript Everywhere" Chapter 11 User Interface and React (^_^)

Translation | "JavaScript Everywhere" Chapter 11 User Interface and React ( _ )

Write at the top

Hello everyone, I am Mao Xiaoyou, a front-end development engineer. An English technical book is being translated.

In order to improve everyone's reading experience, the structure and content of sentences have been slightly adjusted. If you find any flaws in this article, or if you have any comments or suggestions, you can leave a message in the comment area, or add my WeChat: code_maomao, welcome to communicate and learn from each other.

(σ゚∀゚)σ…:*☆Oh, good

Chapter 11 User Interface and React

1979In 2009, the famous Steve Jobs ( Steve Jobs) visited Xerox Parker ( Xerox Parc), where he saw a Altodemonstration of Xerox's personal computer. At that time, other computers were controlled by typing commands, and Altothey used a mouse and had a graphical window interface that could be opened and closed. Jobs Apple Macintoshcontinued to draw on these ideas in his original creation. The original Macpopularity led to UIa proliferation of computers . Today, on a typical day, we may interact with many graphical user interfaces, which may include personal computers as well as smartphones, tablets, ATMand game consoles. The user interface now surrounds us and can be used across various devices, content types, screen sizes, and interactive formats.

For example, I recently went to another city for a meeting. That morning, I woke up and checked the flight status on my phone. I drove to the airport and showed a map on the screen, allowing me to choose the music I was listening to. On the way, I stopped on the ATMplane to retrieve some cash, entered the PINcode and entered the instructions on the touch screen. When I arrived at the airport, I boarded at a check-in counter. While waiting for the bus at the boarding gate, I responded to several emails on my tablet. During the flight, I read a book on the electronic ink display device. After landing, I used an app on my phone to find a car to ride, then stopped for lunch, and selected my order on the display. At the meeting, a slide was projected onto the screen platform, and many of us took notes on laptops. When I returned to my hotel in the evening, through the hotel TV screen menu, I browsed the TV and movie products I found. My day is full of many UIscreen sizes, used to complete tasks related to the core elements of life (such as transportation, finance, and entertainment).

In this chapter, we will briefly introduce JavaScriptthe history of user interface development. After mastering this background knowledge, we will explore Reactthe basics and JavaScriptlibraries that will be used in the rest of this book .

JavaScript sum UI

It was originally designed in 1990the middle of the decade (not well-known, 10 days ) to enhance the Webinterface and provide an embedded scripting language JavaScriptin the Webbrowser. This allows Webdesigners and developers to add HTMLinteractions that cannot be achieved by themselves . Unfortunately, each browser vendor has a different JavaScriptimplementation, so it is difficult to use. This is one of the factors leading to the proliferation of applications designed to work in a single browser.

In 2000the middle of the decade

jQuery(And similar libraries, for example MooTools) became popular. jQueryAllow developers to use simple APIwriting JavaScript, which APIcan run well between various browsers. Soon, we can all delete, add, replace and animate the content on the webpage. Around the same time, Ajax( abbreviation for "asynchronous JavaScriptsum XML") enabled us to fetch data from the server and inject it into the page. The combination of these two technologies Webprovides an ecosystem for creating powerful interactive applications.

As the complexity of these applications increases, so does the need for organization and sample code. By 2010the beginning of the decade, frameworks such as Backbone, Angularand Emberbegan to dominate the JavaScriptapplication domain. These frameworks work by imposing structure in the framework code and implementing common application patterns. These frameworks are usually MVCmodeled according to the software design module, view, and controller ( ) mode. Each framework Webregulates all layers of the application and provides a structured way to handle templates, data, and user interaction. Although this has many benefits, it also means that the workload of integrating new or non-standard technologies may be large.

At the same time, desktop applications continue to be written in system-specific programming languages. This means that developers and teams are often forced to make one or two style choices ( Macapplication or Windowsapplication, Webapplication or desktop application, etc.). The mobile application is in a similar position. WebThe rise of responsive design means that designers and developers can Webcreate truly incredible websites and applications for mobile browsers, but choosing to build only-based Webapplications locks them out of the mobile platform application repository. Apple'S iOSapplications are written in Objective C(and more recently Swift) and Androidrely on Javaprogramming languages ​​(not to JavaScriptbe confused with our friends ). This means that by the HTML, CSSand JavaScriptthe composition Webis the only true cross-platform user interface platform.

JavaScript's declarative interface

In 2010the early years, Facebookdevelopers JavaScriptfaced challenges in the organization and management of their code. In response, a software engineer Jordan Walkein Facebookthe PHPlibrary XHPinspired to write next React. The difference Reactfrom other popular JavaSriptframeworks is that it only focuses on UIpresentation. To this end, Reacta "declarative" programming approach is adopted, which means that it provides an abstraction that allows developers to focus on the described UIstate.

With the rise of Reactand similar libraries (for example Vue.js), we have seen UIchanges in the way developers write . These frameworks provide a way to manage UIstate at the component level . This makes the user feel smooth about the application, while providing an excellent development experience. With tools such as those for building desktop applications Electronand those for cross-platform native mobile applications React Native, developers and teams can now leverage these paradigms in all their applications.

React is enough

In the remaining chapters, we will rely on Reactlibraries to build ours UI. You don't need to have any Reactexperience in using it, but before using it, if you have some understanding of the grammar, it will be helpful to use it. For this, we will use to create-react-appbuild a new project. create-react-appIt is Reacta tool developed by the team, which allows us to quickly build a new Reactproject and help abstract the underlying build tools, such as Webpackand Babel.

cdEnter the project directory in the terminal application and run the following command, which will just-enough-reactcreate a new Reactapplication in the folder named :

$ npx create-react-app just-enough-react
$ cd just-enough-react

Running these commands will just-enough-reactoutput a directory in which contains all the project structure, code dependencies and development scripts used to build a fully functional application. Start the application by running the following command:

$ npm start

Now our Reactapplication will be http://localhost:3000visible on the browser (picture 11-1).

Picture 11-1input npm startwill start the default in the browsercreate-react-app

Now, we can src/App.jsstart editing our application by changing the file. This file contains our main Reactcomponents. After some dependencies are required, it contains a HTMLfunction that returns some tokens similar to :

function App() {
    
    
  return (
   // markup is here
  )
} 

The mark used in the component is called JSX.

JSXIs a similar XML-based XMLgrammar that allows us to accurately describe UIand combine it with JavaScriptuser actions in the file. If you understand HTML, the choice JSXis just to learn some small differences. The biggest difference in this example is HTMLthat the classattributes are classNamereplaced to avoid JavaScriptconflicts with the class syntax.

JSX?

If, like me, you come from the background of network standardization and strict separation of concerns, then you may find this annoying. I admit that JSXwhen I first encountered it, I immediately strongly disliked it. However, UIthe coupling of logic and presentation output provides a number of compelling advantages that may grow over time.

Let's Hello Worldstart customizing our application by removing most of the style code and simplifying it to a simple " !":

import React from 'react';
import './App.css';

function App() {
    
    
  return (
   <div className="App">
    <p>Hello world!</p>
   </div>
  );
}

export default App; 

You may notice JSXthe tags that encapsulate all of our content. Each React UIcomponent must be contained within a parent HTMLelement or use a Reactfragment, which represents a non- HTMLelement container, for example:

function App() {
    
    
  return (
   <React.Fragment>
    <p>Hello world!</p>
   </React.Fragment>
  );
} 

About Reactone of the most powerful features is that we can be enclosed in braces {} is directly in JSXuse JavaScript. Let's update the Appfunction to use some variables:

 function App() {
    
    
  const name = 'Adam'
  const now = String(new Date())
  return (
   <div className="App">
    <p>Hello {
    
    name}!</p>
    <p>The current time is {
    
    now}</p>
    <p>Two plus two is {
    
    2+2}</p>
   </div>
  );
} 

In the previous example, you can see that we used it directly in the interface JavaScript. How cool is it?

ReactAnother useful feature is the ability to turn each UIfunction into its own component. A good rule of thumb is that if UIone aspect of it operates in an independent manner, it should be separated into its own components. Let's create a new component. First, src/Sparkle.jscreate a new file in and declare a new function:

import React from 'react';

function Sparkle() {
    
    
  return (
   <div>

   </div>
  );
}

export default Sparkle;

Now let's add some features. Whenever the user clicks a button, it will add a flashing emoji (a key feature of any application) to our page. In order to do this, we will import Reactthe useStatecomponent and define some initial state for the component, the initial state will be an empty string (in other words, no flicker).

import React, {
    
     useState } from 'react';

function Sparkle() {
    
    
  // declare our initial component state
  // this a variable of 'sparkle' which is an empty string
  // we've also defined an 'addSparkle' function, which
  // we'll call in our click handler
  const [sparkle, addSparkle] = useState('');

  return (
   <div>
    <p>{
    
    sparkle}</p>
   </div>
  );
}

export default Sparkle; 

What is State?

We will 15introduce more details in Chapter 1 state, but for now, you only need to know that stateful components can change the current state of any information in the component.

For example, if a UIcomponent has a check box, its state is when it is selected and its state is when it is truenot false.

Now, we can onClickcomplete the component by adding functional buttons. Note the camel case naming, which JSXis required in:

import React, {
    
     useState } from 'react';

function Sparkle() {
    
    
  // declare our initial component state
  // this a variable of 'sparkle' which is an empty string
  // we've also defined an 'addSparkle' function, which
  // we'll call in our click handler
  const [sparkle, addSparkle] = useState('');

  return (
    <div>
      <button onClick={
    
    () => addSparkle(sparkle + '\u2728')}>
        Add some sparkle
      </button>
      <p>{
    
    sparkle}</p>
    </div>
  );
}

export default Sparkle; 

To use our component, we can import it into a src/App.jsfile and declare it as an JSXelement as follows:

import React from 'react';
import './App.css';

// import our Sparkle component
import Sparkle from './Sparkle'

function App() {
    
    
  const name = 'Adam';
  let now = String(new Date());
  return (
   <div className="App">
    <p>Hello {
    
    name}!</p>
    <p>The current time is {
    
    now}</p>
    <p>Two plus two is {
    
    2+2}</p>
    <Sparkle />
   </div>
  );
}

export default App;

Now, if you visit our app in a browser, you should see our button and be able to click it to add the sparkling emoji to the page! This is one Reactof the real super powers. We are able to re-render individual components or components (pictures 11-2) independently of the rest of the application .

Figure 11-2Clicking the button will update the component state and add the content to our page

Now, we have create-react-appcreated a new application, updated the application components JSX, created a new component, declared the component state, and dynamically updated the component. With a basic understanding of these basics, we are now ready to Reactuse JavaScriptdeclarative development UI.

in conclusion

We are surrounded by user interfaces on various devices. JavaScriptAnd Webtechnology provides unparalleled opportunities to develop these interfaces on multiple platforms using a single technology. At the same time, Reactand other declarative visual libraries enable us to build powerful dynamic applications. The combination of these technologies allows developers to build amazing things without having to have expertise on each platform. In the following chapters, we will put it into practice by using the interfaces GraphQL APIbuilt for Web, desktop, and mobile applications.

If there is any inadequate understanding, please correct me. If you think it's okay, please like to collect or share it, hoping to help more people.

Guess you like

Origin blog.csdn.net/code_maomao/article/details/110217661