ReactNative Day2

参照:The Introduction

Component

Components in React are more or less self sufficient in that they constitute the presentation (HTML) as well as the behavior (eg. event handlers). They are also composable - meaning we can easily use one component within other component. So how do we create a Component? There are couple common ways how you can create a React component.
接下来说几个方法:

Build Component Class

One way to create a React component is to create an ES6 class and extend React.Component.(使用一个类,以及一个React.Component的拓展就可以了) Each component created using this method should have a render function that returns what the DOM should look like if this component is rendered on the browser. Render函数是用来实现HTML功能的东西。

import React from 'react';

class Component extends React.Component {
    //needs render function
    render() {
        return (
            //return should tell React what the DOM should look like
            //if this component is rendered in the browser
        );
    }
}

Using Component Function

Another common way to create a React component is to create a simple function that takes in a parameter (we call props) (我们吧参数叫做Props)and returns the exact same thing as above - what the DOM should look like if this component is rendered on the browser. 在浏览器中需要展示的时候的样子的代码返回就可以了,上面是render function,这里是直接的function。

function Component(props) {
    return (
        //return should tell React what the DOM should look like
        //if this component is rendered in the browser
    );
}

Note: Components that are user-defined - meaning the components that you and I write and are not available in the React implementation itself - must have first letter capital.

ONE MORE THINGS

Lets get more deep in the above question.
User-Defined Components Must Be Capitalized.用户自定义的组件必须要大写开头。
When an element type starts with a lowercase letter, it refers to a built-in component like <div> or <span> and results in a string 'div' or 'span' passed to React.createElement. Types that start with a capital letter like <Foo /> compile to React.createElement(Foo) and correspond to a component defined or imported in your JavaScript file.
此代码不会按预期运行:

import React from 'react';

// Wrong! This is a component and should have been capitalized:
function hello(props) {
  // Correct! This use of <div> is legitimate because div is a valid HTML tag:
  return <div>Hello {props.toWhat}</div>;
}

function HelloWorld() {
  // Wrong! React thinks <hello /> is an HTML tag because it's not capitalized:
  return <hello toWhat="World" />;
}

为了解决这个问题,我们将重新命名hello,以Hello和使用提到它的时候:

import React from 'react';

// Correct! This is a component and should be capitalized:
function Hello(props) {
  // Correct! This use of <div> is legitimate because div is a valid HTML tag:
  return <div>Hello {props.toWhat}</div>;
}

function HelloWorld() {
  // Correct! React knows <Hello /> is a component because it's capitalized.
  return <Hello toWhat="World" />;
  //感觉这个就是和div类似,Component就是div H1这种吧!
}

🆗,Let's <( ̄︶ ̄)↗[GO!] Go On

The above two approaches are identical except there are certain things that React.Component can do that the function cannot do but we will park that for now and come back to it later in this tutorial.

HelloWorld Begining

Brief Structure

import React from 'react';

function HelloWorld(props){
    //function must return something
    return (
        //return should tell React to render Hello World in the browser
    );
}

The return of this function is telling React what the DOM should look like when this component is rendered on the browser. In case you're using React.Component approach (instead of function approach like above), it's what you return from render function that tells React what the DOM should look like when the component is rendered.
One way to tell React to display the above HTML is by using React.createElement function:

return React.createElement('div', null, 'Hello World');

就是可以直接向上面那样直接crate一个Element div
Notice that React.createElement is a simple JavaScript function which takes three arguments. 三个参数 First argument is the **element **you want to render. In our case it's a div element. Second argument is any **properties **we want to pass to that element. In our case we are not passing anything so it's null. Third argument is the **children **for this component. In this case it's the text we want to display - Hello World. So with this we are telling React to render a div element like this:

<div>
    Hello World
</div>

We can actually write our entire application this way - creating elements, removing elements, appending elements, etc ourselves. As a matter of fact we did write applications this way before all these UI frameworks/libraries started to mushroom.

Good Ol' Days

Let's imagine you have a barebone html file that looks like below. It has a div with id root inside body. Pretty simple.

<html>
    <head></head>
    <body>
        <div id="root"></div>
    </body>
</html>

Now imagine inside the div with id root we want to render another div that says Hello World. The only catch is we want to do that programmatically using pure JavaScript.
To achieve this we can probably do something like this:

//Create a div node and append Hello World text
const helloWorldDiv = document.createElement('div');
helloWorldDiv.append('Hello World');

//Select the root node and append the div created above
const root = document.getElementById('root');
root.appendChild(helloWorldDiv);

Age of React

A simple example like the one above are not that hard to write with pure JavaScript but once your application gets bigger, it gets messier. That's where libraries like React come to the rescue - they hide away from us the messier part of rendering on the browser.

The Core React library itself doesn't really know how to render anything on the browser because it is designed to work in a web browser as well as native applications. Thus the job of rendering your component on the browser is done by another library provided by React team called ReactDOM.

Now let's get back to the HelloWorld React component we created at the top of this page and see how we can use ReactDOM to render that component to the browser.

ReactDOM.render(HelloWorld, document.getElementById('root'))

Here we are calling a function called render on ReactDOM object. The first argument of the function is the component you want to render - in our case HelloWorld. Second argument is a document selector. ReactDOM appends the component we want to display (first argument) as a child of the node returned by the selector (second argument).

Virtual DOM

DOM (Document Object Model) is an object representation of the HTML. To see what it looks like open chrome dev tools (Right Click + Inspect) and type console.dir(document) and hit enter, you will see a JSON-like tree structure with fields and methods. React for it's part maintains a copy of this DOM - what's called a virtual DOM, named so because it's not a real one, it's a virtual copy.

Why does React hold a copy of the DOM? The main reason it maintains a virtual copy of the DOM is to improve performance of the application.
Web applications these days are very complex. User interacts with the app or the app fetches data and based on that the DOM is updated so that users sees the effects of their interaction or new data. This updating of DOM, however, is an expensive operation - creating and removing DOM nodes (like we did with document.createElement('div') above) are expensive. So React optimizes this updating operations using virtual DOM.

The way this roughly works is: when there's anything that will cause a UI to update (called re-render), React first updates its virtual DOM instead of real DOM. Then it compares the virtual DOMs (before and after the update). It has a heuristic algorithm to determine which piece of the DOM might have changed. Once it figures that out, it updates only the changed piece on the real DOM. Again the reason it does this is because updating the DOM is an expensive operation and it wants to optimize this piece so it only updates what is absolutely necessary instead of tearing down the entire DOM and recreating it.

posted @ 2021-12-20 11:34  Indullged  阅读(32)  评论(0编辑  收藏  举报