Elements and Components

const div = React.createElement('div',...)
Copy the code

This is an element (d lowercase).

const Div = ()=>React.createElement('div'..)
Copy the code

This is a component (D capital)

  • What is a component

    Components, conceptually similar to JavaScript functions. It takes an arbitrary input parameter (” props “) and returns a React element that describes what the page displays.

    Components can be understood as parts of a page that can be combined with other components to form a finished page.

    For now, a function that returns a React element is a component. In Vue, a construct option can represent a component.

React Two components

First, function components

The easiest way to define a component is to write a JavaScript function:

function Welcome(props) {
  return <h1>Hello, {props.name}</h1>;
}
Copy the code

This function is a valid React component because it takes only the “props” (representing properties) object with data and returns a React element. This type of component is called a “function component” because it is essentially a JavaScript function.

Class components

You can also use ES6 classes to define components:

class Welcome extends React.Component { render() { return <h1>Hello, {this.props.name}</h1>; }}Copy the code

The above two components are equivalent in React.

Differences and common ground

In common

  1. Whether a component is declared using functions or classes, it must never modify its own props.
  2. All React components must be pure functions and do not modify their own props.
  3. React is a single data stream. If the parent component changes its properties, the child component view is updated.
  4. The props property is passed from the outside, and the state is the component itself. The state can be modified in the component at will

Component properties and state changes update the view

The difference between

  1. Function components perform better than class components because class components are instantiated when used, whereas function components simply execute the function and fetch the result.
  2. To improve performance, use functional components whenever possible

<Welcome />What will it be translated into

  • <div />Translated intoReact.createElement('div')
  • <Welcome />Translated intoReact.createElement(Welcome)
  • Babel Online direct translation

The React. The createElement method of logic

  • If a string ‘div’ is passed, a div is created
  • If a function is passed in, the function is called and its return value is retrieved
  • If a class is passed in, we prefix it with a new, execute the constructor to get the component object, and then call the render method of the object to get the return value

Note: Component names must begin with a capital letter.

React will treat components that begin with a lowercase letter as native DOM tags. For example,

represents an HTML div tag, while
represents a component and needs to use Welcome in scope.

A profound

Class components and function components use props&state

The role of

Props and state are common JavaScript objects. They’re all used to hold information. A component can reference other components. The references between components form a tree structure (component tree). If a lower-layer component needs to use data or methods of the upper-layer component, the upper-layer component can pass the props property of the lower-layer component, so the props is the interface of the component. In addition to using data passed by upper-layer components, a component may also need to maintain administrative data itself, which is its internal interface state. Based on the external interface props and internal interface state, the component calculates the UI of the corresponding interface

I. Props (External Data)

Props is the external data interface of a component. It can only read but not write

  • Class componentsreadProps attribute:this.props.xxx
  • Function componentreadProps parameters:props.xxx
Class Son extends React.Component {render() {return (<div className="Son"> My dad said "{this.props. MessageForSon}" <Grandson messageForSon =" Hello "/> </div>); } const Grandson => {props ="Grandson"> <div className="Grandson", my dad said "{props. Messageforfunctions}" </div>); };Copy the code

Ii. State (Internal data)

State is the component’s internal data interface, which can be read or written

  • The class component reads state:this.stateWrite to,this.setState. Recommend to writethis.setState=()=>{****}Because it’s easier to understandAsynchronous setState
    • setStateAfter that, state will not change immediately. Reading state immediately will fail. SetState (function) is recommended.
    • this.setState(this.state)Not recommended. React doesn’t want us to modify old state (immutable data), common codesetState({n:state.n+1})
  • Function componentsusestateReturns an array with the first item read and the second item written
    • Without this, use parameters and variables

The function component using react.usestate () is an assignment, which returns a new array and then uses destruct assignment. The first element of the array is the assignment value and the second is the modified value

class Son extends React.Component { constructor() { super(); this.state = { n: 0 }; } add() {// this.state.n += 1 // React does not listen to data like Vue. } render() {return (<div className="Son"> Son n: {this.state.n} <button onClick={() => this.add()}>+1</button> <Grandson /> </div> ); } } const Grandson = () => { const [n, setN] = React.useState(0); Grandson :{n} <button onClick={() => setN(n +1)}>+1</button> </div> };Copy the code

Complicated notation for state

Class component writing(Automatic merge)

class Son extends React.Component { constructor() { super(); this.state = { n: 0, m: 0 }; } addN() { this.setState({ n: this.state.n + 1 }); } addM() { this.setState({ m: this.state.m + 1 }); } render() {return (<div className="Son"> n: {this.state.n} <button onClick={() => this.addn ()}>n+1</button> m: {this.state.m} <button onClick={() => this.addM()}>m+1</button> <Grandson /> </div> ); }}Copy the code
  • summary

    The setState of a class component modifies some properties of state, and other properties that are not modified automatically retain the previous properties. The two properties are automatically merged. Note that the attributes of the first layer are merged automatically. If there are properties in n and m, and properties in the object change, the second level properties are not merged automatically, for example

   this.state = {
      n: 0,
      m: 0,
      user: {
        name: "frank",
        age: 18
      }
    };
Copy the code

If you change user.name, n and m are merged automatically, while age is not merged and becomes null

To resolve the problem that layer 2 attributes will not automatically merge, you can use object. assign or… Operator, for example

ChangeUser () {const user = object.assign ({}, this.state.user); user.name = "jack"; this.setState({ user: user }); } / /... ChangeUser () {this.setState({// m and n will not be null user: {... This.state. user, // copy all attributes before name: "jack" // age is null}});Copy the code

The way a function component is written(Does not automatically merge)

const Grandson = () => { const [n, setN] = React.useState(0); const [m, setM] = React.useState(0); Return (<div className="Grandson"> Grandson n:{n} <button onClick={() => setN(n +1)}>n+1</button> m:{m} <button onClick={() => setM(m + 1)}>m+1</button> </div> ); };Copy the code

Function components do not merge automatically at all, requiring operators… Merge, for example

const Grandson = () => { const [state, setState] = React.useState({ n: 0, m: 0 }); Grandson :{state.n} <button onClick={() => setState({... state, n: state.n + 1 })}>n+1</button> m:{state.m} <button onClick={() => setState({... state, m:state.m + 1})</button>> </div> ); };Copy the code

3. State considerations (Class Components)

State cannot be modified directly

Because the component does not re-render. In the example below, n has actually changed, but the UI is not updated automatically, only a call to setState will trigger the UI update. React is not data responsive like Vue. It listens for data changes and triggers view updates

This.setstate = ({n: state.n +1})) {this.setState = ({n: state.n +1});}Copy the code

SetState is asynchronously updating the UI

By calling setState, the component’s state does not change immediately, and reading state immediately fails. Because setState is executed asynchronously and the modified state is placed in a queue, React optimizes the actual execution timing, and React may merge multiple setState changes into a single state change for performance reasons. Note that you cannot rely on the current props to calculate the next state, because updates to the props are also asynchronous. The recommended method is setState(fn function)

The update to State is a shallow merge

When setState is called to modify the state of a component, only the changed state variable is passed in, not the full state of the component, because updating the component state is a Shallow Merge process.

// For example, a component whose state is this.state = {title: 'React', content: 'React is a wonderful JS library! SetState this.setState({title: 'Reactjs'}); // React will merge the new title into the original component state, while keeping the original state content. The merged state is {title: 'Reactjs', content: 'React is an wonderful JS library! '}Copy the code

Using this.setState(this.state) is not recommended

React doesn’t want us to modify old state because state is immutable data. Therefore, it is recommended to preserve the old data while creating a new object to manipulate state. For example, setState ({n: state. The n + 1})

4. Event binding

Class component event binding

Writing method 1: the safest writing method

<button onClick={() => this.addn ()}>n+1</button> This._addn =()=> this.addn () <button onClick={this._addn}>n+1</button>Copy the code

This in addN refers to the global variable window, not recommended

<button onClick={this.addN}>n+1</button>
Copy the code

Use bind to bind the new function to this

<button onClick={this.addN.bind(this)}>n+1</button>
Copy the code

Finally,this points correctly

constructor(){ this.addN = ()=> this.setState({n: {this.state.n + 1}}} // Use the following syntax: addN = () => this.setState({n: this.state.n + 1});Copy the code

In other words, the final form is zero

class Son extends React.Component{
    addN = () => this.setState({n: this.state.n + 1});
    render(){
        return <button onClick={this.addN}>n+1</button>
    }
}
Copy the code

Error: This points to the window

Class Son extends React.Component{addN(){this.setState({n: this.state.n + 1})} functioin(){ this.setState({n: this.state.n + 1}) } }Copy the code

Method 4 VS method 5

  1. The addN function of notation 4 is an attribute of the object itself, meaning that each Son component can have its own addN function, for example, two sons, each will have its own addN function. Because this points to the Son component
  2. The addN function of notation 5 is the common attribute of the object, that is, the attribute on the prototype, that is, in prototype. Means that all Son components share one addN function. Because this refers to the global variable window
  3. The this of all functions is an argument, determined by the call, and therefore mutable
  4. The arrow function’s this remains the same, because arrow functions do not accept this

Introduce this interview question

See link for answers

The interview questions a

SayName :function(){console.log("this.name = "+ this.name); }}; Var name = "name"; function sayName(){ var sss = a.sayName; sss(); //this.name = ? a.sayName(); //this.name = ? (a.sayName)(); //this.name = ? (b = a.sayName)(); //this.name = ? } sayName()Copy the code

The interview questions 2

var length = 10; function fn() { console.log(this.length); } var obj = { length: 5, method: function(fn) { fn(); arguments[0](); // the first argument is fn()}}; obj.method(fn, 1)Copy the code

Five.Props VS state

  • propsIs passed to the component (similar to a function parameter), andstateIs managed within a component by the component itself (similar to variables declared within a function)
  • propsIs the component ofRead-only property, components cannot be modified directlyprops, to modifypropsCan only be modified in the upper component of the component
  • stateIs created in a component, typically inconstructorIn the initializationstate
  • stateMutable is a set of states maintained internally by a component to reflect changes in the component’s UI
  • stateIs changeable,You can modifyEvery time,setStateAsynchronous updatethe

Vue vs. React (Rules vs. Freedom)

The same

  • React represents a component with classes and functions, whereas Vue constructs a component with construction options
  • providecreateElementReact provides the JSX syntax, while Vue provides the template syntax

The difference between

  • React puts HTML in JS, Vue puts JS in HTML.

Conclusion:

  • Vue: I did everything I could for you
  • React: I don’t do anything I can
  • Vue: Write JS in HTML, JS in HTML
  • React: Write HTML in JS