I've been learning React.js recently. Before, I used to write React code in the most native way, but I found it very troublesome to organize it. I heard that it is easy to organize React components with Webpack, so I spent some time learning it and gained a lot. Let’s talk about React A component has its own structure, logic, and style. It depends on some resources and other components. For example, when writing a component, the common way is: - Define the structure through the front-end template engine - Write your own logic in the JS file - Writing component styles in CSS - Solve the interdependencies between modules through libraries such as RequireJS and SeaJS, So what does this look like in React? Structure and logic In the React world, the structure and logic are organized by JSX files. React embeds the template into the logic, implementing a JSX that is a mixture of JS code and HTML. structure In a JSX file, you can define components directly through React.createClass:
In this way, we can easily define a component. The structure of the component is defined in the render function, but this is not a simple template engine. We can use js to conveniently and intuitively manipulate the component structure. For example, I want to add a few nodes to the component: In this way, React allows components to have a flexible structure. So how does React handle logic? logic Anyone who has written a front-end component knows that a component usually needs to respond to its own DOM events and do some processing. If necessary, it also needs to expose some external interfaces. So how do React components achieve these two points? Incident Response For example, if I have a button component, and I need to do some processing logic after clicking it, then the React component will look like this:
Clicking a button should trigger the corresponding logic. A more intuitive way is to bind an onclick event to the button, which contains the logic to be executed:
This implements the response to internal events, but what if you need to expose the interface? Exposing interfaces In fact, now getDragonKilling
Sword is already an interface. What if there is a parent component that wants to call this interface? The parent component looks like this:
If you want to call the component method manually, first set a ref="" attribute on ButtonComponent to mark it. For example, here we set the subcomponent to
It looks cool~ But here comes the question: the parent component wants to be able to call the method when the button is clicked, so what should it do? Configuration parameters The parent component can directly pass the function to be executed to the child component: Then call the parent component method in the child component:
Child components can obtain any parameters passed in when the parent component creates the child component through this.props, so this.props is often used as a configuration parameter. Each person can only receive one Dragon Slaying Sword. The button should be grayed out once it is clicked. A state of whether it has been clicked should be added to the subcomponent. How should this be handled? Component Status In React, each component has its own state, which can be obtained through this.state in its own method, and the initial state is defined by the getInitialState() method. For example, the initial state of the Dragon Sword Button component should be unclicked, so the getInitialState method should define the initial state clicked: false. In the click execution method, the state value should be modified to click: true:
In this way, the maintenance of the click state is completed, so the style of the node should also be maintained according to the state in the render function. For example, if the button is set to disabled here, the render function should add the corresponding judgment logic:
Sections Here is a brief introduction to managing the structure and logic of components through JSX. In fact, React also defines many methods for components, as well as the life cycle of the components themselves, which makes the logical processing of components more powerful. #p# Resource loading CSS files define the styles of components. Current module loaders are usually able to load CSS files, and if they cannot, corresponding plug-ins are generally provided. In fact, CSS and images can be regarded as a kind of resource, because they generally do not need to be processed after loading. React does not do anything special in this regard. Although it provides an Inline Style method to write CSS in JSX, it is estimated that not many people will try it. After all, CSS styles are no longer just simple CSS files. They are usually pre-processed with Less, Sass, etc., and then post-processed with postcss, myth, autoprefixer, cssmin, etc. Resource loading is generally done simply and crudely using module loaders. Component Dependencies The processing of component dependencies is generally divided into two parts: component loading and component use. Component loading React does not provide a related component loading method. It still needs to be introduced through the <script> tag, or the component's JSX and resource files need to be loaded using a module loader. Component UsageIf you are careful, you will find that there are actually examples of its use before. If you want to use another component in one component, such as using ChildComponent in ParentComponent, you only need to write <ChildComponent /> in the render() method of ParentComponent, and you can pass some parameters when necessary. doubtAt this point, you will find a problem. React only handles structure and logic, and does not care about resources or dependencies. Yes, React has nearly 20,000 lines of code, and does not even provide a module loader. What's more, unlike Angularjs, jQuery, etc., it does not come with any scaffolding... There is no Ajax library, no Promise library, and nothing else... Virtual DOMWhy is it so big? Because it implements a virtual DOM. What does the virtual DOM do? Let's start with the browser itself. As we know, when a browser renders a web page, after loading an HTML document, it will parse the document and build a DOM tree, which will then be combined with the CSSOM tree generated by parsing CSS to produce the fruit of love - the RenderObject tree, and then render the RenderObject tree into a page (of course, there may be some optimizations in the middle, such as the RenderLayer tree). These processes all exist in the rendering engine, which is separated from the JavaScript engine (JavaScriptCore or V8) in the browser. However, in order to facilitate JS to operate the DOM structure, the rendering engine will expose some interfaces for JavaScript to call. Since these two parts are separated from each other, communication comes at a cost, so the performance of JavaScript calling the interface provided by DOM is not very good. Various performance optimization best practices are also trying to reduce the number of DOM operations as much as possible. What does the virtual DOM do? It implements the DOM tree directly with JavaScript (roughly). The HTML structure of the component does not directly generate the DOM, but is mapped to a virtual JavaScript DOM structure. React then implements a diff algorithm on this virtual DOM to find the smallest change, and then writes these changes to the actual DOM. This virtual DOM exists in the form of a JS structure, so the computing performance will be better, and because the number of actual DOM operations is reduced, the performance will be greatly improved. I understand the logic, but why don’t we have a module loader? So we need Webpack Let’s talk about WebpackWhat is Webpack?In fact, it is a packaging tool, not a module loader like RequireJS or SeaJS. By using Webpack, it can handle dependencies like Node.js, and then resolve the dependencies between modules and package the code. Installing WebpackFirst you need Node.js Then install webpack via npm install -g webpack. You can also use gulp to handle webpack tasks. If you use gulp, use npm install --save-dev gulp-webpack Configure WebpackThe Webpack build process requires a configuration file. A typical configuration file is like this:
The packaging behavior of Webpack is configured here, which is mainly divided into several parts:
Of course, Webpack has many other configurations, please refer to its configuration documentation for details Execute packagingIf you install webpack via npm install -g webpack, you can directly execute the packaging command through the command line, such as this:
This will read the webpack.config.js in the current directory as the configuration file to perform packaging operations If you use the gulp plugin gulp-webpack, you can write the gulp task in the gulpfile:
#p# Component WritingUsing Babel to improve your imageWebpack allows us to use the CommonJS specification of Node.js to write modules. For example, a simple Hello world module can be processed like this:
Wait, this is no different from the previous way of writing, still not cool... Programmers should write code like geeks, more cool than cool, this is too low. Now it's ES6, React code should also be written in ES6, babel-loader does this. Babel can convert ES6 code into ES5. First you need to install it through the command npm install --save-dev babel-loader, and you can use it after the installation is complete. One way to use it is to configure it in the loaders of webpack.config.js as introduced before, and the other is to use it directly in the code, such as:
So how can we use Babel to improve the quality of our code? Let’s modify the previous HelloWorld code:
In this way, if you need to import the HelloWorldComponent component in other components, you only need to:
How about it? Isn't it more cool? By importing the module, you can also directly define the inheritance relationship between classes. There is no need for getInitialState here . Just use this.state = xxx in the constructor . Of course, Babel brings more than that. With its help, you can try many excellent ES6 features, such as arrow functions. The characteristic of arrow functions is that the internal this is consistent with the external one, so you can say goodbye to that and _this.
There are many others, please refer to Babel's learning documentation for details Style WritingI am a patient who is strongly dependent on Less. If I write CSS directly without Less, I will feel weak, unwilling to work, and irritable. I also don’t like to add prefixes when writing Less. I usually handle it directly with gulp+less+autoprefixer. So how should I write it in the React component organized by Webpack? Yes, loader is still used You can add Less configuration to loaders in webpack.config.js:
With this configuration, you can directly introduce the Less style into the module code:
otherWebpack's loader provides a lot of help for React componentization. For example, images also provide relevant loaders:
For more loaders, please visit webpack's wiki ##Live debugging of React components under Webpack Another powerful combination of Webpack and React is that after modifying the component source code, the changes can be synchronized to the page without refreshing the page. Here we need to use two libraries: webpack-dev-server and react-hot-loader. First you need to install these two libraries, npm install --save-dev webpack-dev-server react-hot-loader After the installation is complete, it is time to start configuration. First, you need to modify the entry configuration:
In this way, you can specify the server corresponding to the resource hot start, and then configure react-hot-loader to the loaders configuration. For example, all my component codes are placed in the scripts folder:
Finally, configure plugins, add hot replacement plugins and error prevention plugins:
The configuration is now complete, but now you need to start a server for debugging, and the previous configuration maps it to http://localhost:3000, so start a server on local port 3000 and create a server.js in the project root directory:
In this way, you can start the debugging server on the local port 3000. For example, if my page is index.html in the root directory, you can directly access the page through http://localhost:3000/index.html. After modifying the React component, the page will also be modified synchronously. It seems that websocket is used here to synchronize data. The picture shows a simple effect:
FinishReact's component-based development is very interesting, and Webpack makes it easier to write and manage React components. This only covers a small part of React and Webpack. There are more best practices to be discovered on the road of learning. |
<<: In the App Era, Do Mobile Browsers Still Have a Chance?
>>: W3C releases Mobile Checker
[Girls' Emotions] How to become a charming go...
Live streaming is a stopover on the journey from ...
In January 2019, the number of Xiaohongshu users ...
Produced by: Science Popularization China Produce...
According to foreign media reports, the British g...
(Photo source: China Meteorological News Agency) ...
We use our noses every day, for breathing, smelli...
Recently, Porsche announced its sales data for 20...
[[124859]] via:appying In the mobile Internet ind...
Foreign website Subscribe released a video compari...
Affected by the remnant circulation of Typhoon Du...
Liang Jun, president of LeTV Zhixin, once said th...
Edit: Corner On February 22, according to the Nan...
Buy, buy, buy!!! This phrase has been very popular...
Lebo Capital founder Yang Ning's recent remar...