What is a component, its characteristics and classification

component

A component is a wrapper around a specific function that is used to break up the UI.

The characteristics of

  • independent
  • reusable
  • Can be combined

classification

  • Base component: refers toinput,buttonThis base tag, as well as the generic UI components encapsulated by ANTD
  • Business Components: Business abstraction UIs composed of base components. For example, the drop-down list contains information about all departments of company A
  • Block components: UI blocks composed of base component components and business components
  • Page component: The final page presented to the user, usually corresponding to a routing rule

There are two ways to create the React component

(1) Use JS functions to create components

(2) Create a component using class in JS

import React from 'react'
import ReactDOM from 'react-dom'

const title = <h1>React defines components in two ways</h1>

// Define a functional component
const Com1 = () = > {
  return <div>The first functional component</div>
}

// Define a class component
class Com2 extends React.Component {
  render () {
    return <div>The first class component</div>}}const content = (
  <div>{title} // Use double label rendering<Com1></Com1>
    <hr />// Use single label rendering<Com2 />
  </div>
)

ReactDOM.render(content, document.getElementById('root'))
Copy the code

Functional components – Components created using JS functions (or arrow functions)

The default conventions

  • Function names must start with a capital letter. React is distinguished by thiscomponentandOrdinary HTML)
  • There must be a return value (representing the COMPONENT’s UI structure; Return null if nothing needs to be rendered.)
// 1. Create a component using a normal function:
function Hello() {
  return <div>This is my first function component!</div>
}

// 2. Use the arrow function to create a component:
const Hello = () = > <div>This is my first function component!</div>
Copy the code

Class components – Create components with class

format

// import { Component } from 'react'
// class extends Component {
import React form 'react'
classThe name of the classextends React.Component {
  // ... 
  render () {
    returnUI structure of this component}}Copy the code

Pay attention to the point

  • Class names must begin with a capital letter
  • Extends is a keyword that implements inheritance between classes. Class components should inherit from the React.componentparent class to use methods or properties provided in the parent class.
  • The class component must provide the Render method, which must return a value representing the UI structure of the component. Render is executed once when the component is created

Stateful components and stateless components

What is a state?

State is the data that describes the state of something at a given moment (e.g., the number of books in stock on November 12).

The characteristics of

The state can be changed, and the view will change accordingly

What are stateful and stateless components

  • Stateful component: A component that can define state. A class component is a stateful component.

  • Stateless component: A component that cannot define state. Function components are also called stateless components

React 16.8 introduced React Hooks, which enable functional components to define their own state.

The state of the class component

There are two ways to define state

(1) state = object

(2) Initialize the constructor with this.state= object

import React from "react";
export default class Hello extends React.Component {
  // 1
  state = {
    list: [{ id: 1.name: "Tomorrow will be better."}, {id: 2.name: "Not to forget tonight."}].isLoading: true
  };
  // 2. Constructor
  constructor() {
    this.state = {
      list: [{ id: 1.name: "Tomorrow will be better."}, {id: 2.name: "Not to forget tonight."}].isLoading: true}}}Copy the code

Used in the view

  render() {
    return (
      <>
        <h1>Playlists - {this. State. The count}</h1>
        <ul>
          {this.state.list.map((item) => (
            <li key={item.id}>{item.name}</li>
          ))}
        </ul>
        <div>{this.state.isLoading ? "Loading" : "loading completed "}</div>
      </>
    );
  }
Copy the code

event

format

< element name 1={event handler 1} Event name 2={event handler 2} ></ element >

(Note :React event names use hump nomenclature, such as onMouseEnter, onFocus, onClick……)

import React from 'react'
import ReactDOM from 'react-dom'

const title = <h1>Events in React</h1>


export default class Hello extends React.Component {
  fn() {
    console.log('mouseEnter events')}render() {
    return (
      <div
        onClick={()= >Console. log('click event ')} onMouseEnter={this.fn} can handle mouse entry or click events</div>)}}const content = (
  <div>
    {title}
    {<Hello />}
  </div>
)

ReactDOM.render(content, document.getElementById('root'))
Copy the code

Note:

  • Event names are small hump naming format
  • Add methods to the class
  • This.fn does not enclose parentheses

The event object

In React, it is obtained from the parameter to the event handler.

  handleClick(e)=> {
    e.preventDefault()
    console.log('Click event triggered', e)
  }
	render() {
  	return (<div>
            <button onClick={(e)= >{console.log(' button clicked ', e)}}> button</button>
    				<a href="http://itcast.cn/" onClick={this.handleClick}>Wuhan dark horse</a>
  			</div>)}}Copy the code

Event Handling – This points to the problem

class App extends React.Component {
  state = {
    msg: 'hello react'
  }
  handleClick() {
    console.log(this) // Where this is? undefined
  }
  render() {
    console.log(this) // Where this is? Current React component
    return (
      <div>// This. HandleClick is not called. It has no event source bound to the call<button onClick={this.handleClick}>Am I</button>
      </div>)}}Copy the code

The analysis reason

  • Function call mode for event handlers. In strict mode, this points toundefined
  • The Render function is called by the component instance, so this in the render function refers to the current component

Event Handling – This points to the solution

(1) Add arrow function in outer scope (principle: this in arrow function refers to this in outer scope)

class App extends React.Component {
  state = {
    msg: 'hello react'
  }
  handleClick() {
    console.log(this.state.msg)
  }
  render() {
    return (
      <div>
        <button onClick={()= >{this. HandleClick ()}} > point me</button>
      </div>)}}Copy the code

(2) function.prototype.bind ()

class App extends React.Component {
  state = {
    msg: 'hello react'
  }
  handleClick() {
    console.log(this.state.msg)
  }
  render() {
    return (
      <div>
        <button onClick={this.handleClick.bind(this)}>Am I</button>
      </div>)}}Copy the code

(3) Class instance method

class App extends React.Component {
  state = {
    msg: 'hello react'
  }
// Class instance method
  handleClick = () = > {
    console.log(this.state.msg)
  }
  render() {
    return (
      <div>
        <button onClick={this.handleClick}>Am I</button>
      </div>)}}Copy the code

Component status – Modification status

setState

Syntax :this.setState({partial data to be modified})

Effect: Modify state; Update the UI

state = {
  count: 0 
};

this.setState({
  count: this.state.count++
})
Copy the code

Note: The react core concept is immutable

Do not directly modify the current state value, but create a new state value to override the old value.

Two ways to get the value of a form element

  • Find the form element directly for DOM manipulation -> Uncontrolled components
  • Bind form element values to react state to synchronize user changes to state. Let components be controlled by React –> Controlled components

Uncontrolled component -ref

Use steps:

(1) Import method. import { createRef } from ‘react’

(2) Call the createRef method to create a reference, assuming the name is refDom. const refDom = createRef()

(3)refDom sets the ref attribute to the form element.

(4) Obtain the value through refdom.current. Value. console.log(this.refDom.current.value)

// 1. Import method
import { createRef } from 'react'

class Hello extends Component {
  // 2. Call createRef to create a reference
  txtRef = createRef()

  handleClick = () = > {
    // 4. Run the. Current. Value command to obtain the value
    console.log(this.txtRef.current.value)
  }

  render() {
    return (
      <div>
      	<h1>How to get values in input - uncontrolled component-ref</h1>
         {/* 3. Set the ref attribute */ to the form element}
        <p><input type="text" ref={this.txtRef}/></p>
        <button onClick={handleClick}>Gets the value of the text box</button>
      <div>
    )
  }
}
Copy the code

The controlled components

Use steps:

  • Define the state in state

  • Do two things with form elements

    (1) Set value to the state defined above

    (2) Bind the onChange event and use setState to change the status value in the callback

class App extends React.Component {
  state = {
    // 1. Define the state in state
    msg: 'hello react'
  }

  handleChange = (e) = > {
    this.setState({
      msg: e.target.value})} handleClick = () => {console.log(this.state.msg)
  }

  render() {
    return (
      <div>
      	<h1>How do I get values in input - controlled components</h1>
        <p>{/* 2. Do two things with form elements */}<input type="text"
							value={this.state.msg}
							onChange={this.handleChange}
						/>
        </p>
        <button onClick={handleClick}>Gets the value of the text box</button>
      <div>
    )
  }
}
Copy the code

Common controlled components

Different types of form elements have different formats for controlled processing:

(1) Text box, text field, drop-down box: value attribute + onChange event

(2) Check box: Checked property + onChange event

(3) Radio button group: Checked properties + onChange event

import React from 'react'
import ReactDOM from 'react-dom'

class App extends React.Component {
  state = {
    username: ' '.desc: ' '.city: '2'.isSingle: true.gender: 'male'
  }

  handleName = (e) = > {
    this.setState({
      username: e.target.value
    })
  }

  handleDesc = (e) = > {
    this.setState({
      desc: e.target.value
    })
  }

  handleCity = (e) = > {
    this.setState({
      city: e.target.value
    })
  }

  handleSingle = (e) = > {
    this.setState({
      isSingle: e.target.checked
    })
  }

  hGender = (e) = > {
    this.setState({
      gender: e.target.value
    })
  }

  render () {
    return (
      <div>Name:<input
          type="text"
          value={this.state.username}
          onChange={this.handleName}
        />
        <br />Description:<textarea value={this.state.desc} onChange={this.handleDesc} />
        <br />City:<select value={this.state.city} onChange={this.handleCity}>
          <option value="1">Beijing</option>
          <option value="2">Shanghai</option>
          <option value="3">Guangzhou</option>
          <option value="4">shenzhen</option>
        </select>
        <br />Single or not:<input
          type="checkbox"
          checked={this.state.isSingle}
          onChange={this.handleSingle}
        />
        <br />
        <input
          type="radio"
          name="gender"
          value="Male"
          checked={this.state.gender= = ='male'}
          onChange={this.hGender}
        />{'}<input
          type="radio"
          name="gender"
          value="Female"
          checked={this.state.gender= = ='woman'}
          onChange={this.hGender}
        />{'} female</div>
    )
  }
}

ReactDOM.render(<App />.document.getElementById('root'))

Copy the code