A concept,

React.js is a JavaScript library for building user interfaces, with page elements written and generated by JSX.

Second, the characteristics of

  • Declarative Design — Creating interactive UIs is a breeze. Design a concise view of every state in your app. React effectively updates and renders components correctly when data changes.
  • Efficient −React emulates the DOM(Virtual DOM)To minimize interaction with the DOM.
  • JSX − JSX is an extension of the JavaScript syntax. JS uses XML syntax to write user interfaces and makes full use of THE powerful features of JS to operate user interfaces(At compile time, translate the XML syntax into JS, which generates the element through createElement).
  • Data – Unlike the two-way binding feature of vue. js data, React data is changed bysetStateThe trigger; The form also has no way to get input data directly and must listen for the input change event, which is triggered by setState.

Third, build the project

Use create-React-app on NPM to quickly build react projects. Subsequent practices can be written in the project and previewed in real time in the browser.

cnpm install -g create-react-app
create-react-app my-app
Copy the code

The Create React App scaffolding uses Webpack Development Server (WDS) as the Development Server, so after editing the code, simply save the file and the React App refreshes automatically.

Fourth, element rendering

Unlike the browser DOM element, the React element is actually a regular JS object (virtual DOM). The React DOM ensures that the data content of the browser DOM is consistent with the React element.

The reactdom. render method takes two arguments:

  • The root component
  • DOM node to be mounted

1. Render elements into the DOM

// Add a 
      
with id="example" as the root node in an HTML page
<div id="example"></div> // Write elements using JSX and render them to the page using the reactdom.render () method const element = <h1>Hello, world!</h1>; ReactDOM.render( element, document.getElementById('example'));Copy the code

Update element rendering

React elements are immutable. Unable to change the contents or attributes of an element after it has been created. Currently, the only way to update the interface is to create a new element and pass it to the reactdom.render () method.

// Create a react.componentes6 class
class Clock extends React.Component {
  render() {
    return (
      <div>
        <h1>Hello, world!</h1>
        <h2>Is now a {this. Props. Date. ToLocaleTimeString ()}.</h2>
      </div>); }}function tick() {
  ReactDOM.render(
    <Clock date={new Date()} / >.document.getElementById('example')); }// Call reactdom.render () every second with setInterval()
setInterval(tick, 1000);
Copy the code

The React DOM first compares the sequence of elements and only updates the changed parts during rendering.

Five, the JSX

  1. In React, JSX is recommended for writing page elements; JSX executes faster because it is optimized after being coded into JavaScript code.
  2. In a project, if we need to use JSX, then<script>The type attribute of the tag needs to be set to text/ Babel.
  3. Since JSX is JavaScript, some identifiers like class and for are not recommended as XML attribute names. Instead, React DOM usesclassNamehtmlForTo do the corresponding properties. At the same time, adding custom attributes is requireddata- Prefix.
Hello, World

is a piece of JSX code that Babel will eventually translate to:

React.createElement(
  'div'.null.'Hello, World'
)
Copy the code

React.createelement () takes three arguments:

  • JSX element tag
  • JSX element receives an attribute, Object Object
  • Contents wrapped by JSX elements (child)

React.createelement () checks the arguments to make sure the code isn’t buggy and creates the React Element object; React will take these objects and build the DOM.

{
  type: 'div'.props: {
    children: 'Hello, World'}};Copy the code

Using JavaScript expressions in JSX:

// Expression, written in curly braces {}, can also dynamically insert variable values in {}
var content = 'hjj';/ / variable
ReactDOM.render(
    <div>
      <h1>{1 + 1}</h1>
      <h1>{content}</h1>
    </div>
    ,
    document.getElementById('example'));If else statements cannot be used in JSX
<h1>{i == 1 ? 'True! ' : 'False'}</h1>

CamelCase syntax is recommended for setting inline styles. React automatically adds px after specifying the element number
var myStyle = {
    fontSize: 100.color: '#FF0000'
};
ReactDOM.render(
    <h1 style = {myStyle}>Novice tutorial</h1>.document.getElementById('example'));// Comments need to be enclosed in curly braces
{/ * comment... * /}

/ / array
var arr = [
  <h1>Novice tutorial</h1>.<h2>Learning is not only technology, but also dream!</h2>,]; ReactDOM.render(<div>{arr}</div>.document.getElementById('example'));// Use JSX in JSX to write arbitrary level HTML structure
render() {
    const element = <li>Hello, World</li>
    return (
      <div>
        <ul>
          {element}
        </ul>
      </div>)}// Add node attributes to JSX, all attributes should be changed to camel name, such as onclick to onclick
 const element = <div dataIndex="0">Hello, World</div>;
Copy the code

Components & Props

1. Function Definitions (Functional components)

function HelloMessage(props) {
    return <h1>Hello {props.name}!</h1>;
}
const element = <HelloMessage name="Runoob"/>;
Copy the code

2, ES6 Class Definition (Class Component)

class Todo extends React.Component {
  render() {
    return <li>Hello, {this.props.content}</li>;
  }
}

<Todo content="Figure sparrow" />
Copy the code

Native HTML element names start with a lowercase letter, while custom React class names start with an uppercase letter.

3. Composite components

// Create multiple components to compose a component, that is, separate the different function points of the component
function Name(props) {
    return <h1>Site name: {props. Name}</h1>;
}
function Url(props) {
    return <h1>Url: {props. Url}</h1>;
}
function App() {
    return (
    <div>
        <Name name="Rookie Tutorial" />
        <Url url="http://www.runoob.com" />
    </div>
    );
}
Copy the code

4. Default Props

class HelloMessage extends React.Component {
  render() {
    return (
      <h1>Hello, {this.props.name}</h1>
    );
  }
}
 
HelloMessage.defaultProps = {// Set the default value for props using the component class defaultProps property
  name: 'Runoob'
};
const element = <HelloMessage/>;
Copy the code

Passing a key attribute to a component is not incorporated into the props object, so we don’t get the key attribute in the child component.

State and life cycle

React treats a component as a State machine. Achieve different states by interacting with the user, and then render the UI to keep the user interface and data consistent.

1. Simple use

class Clock extends React.Component {
  constructor(props) {
    super(props);
    this.state = {date: new Date(a)}; }render() {
    return (
      <div>
        <h1>Hello, world!</h1>
        <h2>Is now a {this. State. The date. ToLocaleTimeString ()}.</h2>
      </div>); }}Copy the code

2. Life cycle function

  • mount

    Constructor () : You do not need to define this method if you do not need to initialize State when creating a component;

    Render () : render content;

    ComponentDidMount () : After a component is mounted to a DOM node, this is where it usually gets server-side data, etc.

  • uninstall

ComponentWillUnmount () : Before a component is unmounted from a DOM node, it is used to destroy memory leaks such as timers.

3. Add lifecycle methods to the class & update State

class Clock extends React.Component {
  constructor(props) {
    super(props);
    this.state = {date: new Date(a)}; }// The timer is generated when the DOM is first loaded -- mount
  componentDidMount() {
    this.timerID = setInterval(
      () = > this.tick(),
      1000
    );
  }
 // Clear timer when DOM is removed
  componentWillUnmount() {
    clearInterval(this.timerID);
  }
 
  tick() {
    this.setState({// Update State so that the page content can change after rendering
      date: new Date()}); }Copy the code

List and Key

render() {
    const todoList = ["Figure sparrow"."Tootlark Writing Tool."."The Tooquine Community"."Graph document"];
    return (
      <ul>
        {todoList.map((todo, index) => (
          <Todo content={todo} key={index} />
        ))}
      </ul>
    );
  }
Copy the code

Tips:

  • If the list can be reordered, it is not recommended to use index as key for sorting, as this will result in slow rendering;
  • The key is not passed to the sub-components as props. React excludes the key from the props when the component is compiled.