React starts from scratch

Keywords: Javascript node.js React

React starts from scratch

4.1 introduction to react components

  • Using React is using components

  • Component represents some functions in a page

  • Combine multiple components to achieve complete page functions

    Reusable, independent and composable

4.2 two creation methods of react component

4.2.1 creating with functions

Function component: a component created using JS functions (or arrow functions)

  • Function names must start with an uppercase letter in order to distinguish between components and ordinary React elements

  • A function component must have a return value that represents the structure of the component

  • If the return value is null, nothing will be rendered

    Use the function name as the component label name. The component label can be single label or double label

    function Hello() {
    	return <div>This is a function component</div>;
    }
    //Const Hello = () = > < div > this is a function component < / div >
    ReactDOM.render(<Hello />, document.getElementById("root"));
    
    

4.2.2 create using class

Class component: a component created using the class of ES6

  • Class names must begin with an uppercase letter

  • Class component inherits the React.Component parent class in order to use the methods and properties provided in the parent class

  • Class component must provide render() method

  • The render() method must have a return value indicating the component structure

    class Hello extends React.Component {
    	render() {
    		return <div>Class component</div>
    	}
    }
    ReactDOM.render(<Hello />, document.getElementById("root"))
    
    

4.2.3 the extracted components are independent JS files

  1. Create Hello.js
  2. Import React in Hello.js
  3. Create a component (function or class)
  4. Export the component in Hello.js
  5. Import the Hello component in index.js
  6. Rendering Components

Hello.js

import React from 'react'


// Create component
class Hello extends React.Component{
    render() {
        return (
            <div>Detached JS Components in</div>
        )
    }
}

// Export components
export default Hello

index.js

import React from "react"
import ReactDOM from "react-dom"
import "./index.css"

// Import Hello components
import Hello from "./Hello"

// Rendering Components 
ReactDOM.render(<Hello />, document.getElementById("root"))

4.3 React event handling

4.3.1 event binding

on + event name = {event handler}, the event adopts hump naming method

For example, onclick = {() = > {}}

// Event handling through class react

class Opp extends React.Component {
	// Event handler
	handleClick() {
		console.log("Click event")
	}
	render() {
		return <button onClick={this.handleClick}>Little look</button>
	}
}
ReactDOM.render(<Opp />, document.getElementById("root"))

//Binding events through function components
function Opp() {
	function handleClick() {
		console.log("Function click event")
	}
	return <button onClick={handleClick}>A little</button>
}
ReactDOM.render(<Opp />, document.getElementById("root"))

4.3.2 event object

The event object can be obtained through the parameters of the event handler

Event objects are called composite events and are compatible with all browsers

// react event object

class Opp extends React.Component {
	handleClick(e) {
		// Organize browser default behavior (prevent jump)
		e.preventDefault()
		console.log("a Click event for label")
	}
	render() {
		return (
			<a href='http://baidu.com' onClick={this.handleClick}>
				Event object
			</a>
		)
	}
}

4.4 stateful and stateless components

  • Function components are called stateless components, and class components are called stateful components
  • Status is data
  • The function component has no state and is only responsible for static data display
  • Class component has status and is responsible for updating UI dynamically

4.5 state and setState in components

4.5.1 basic use of state

  • Status, that is, data, is private data inside the component and can only be used inside the component
  • The value of state is an object, indicating that there can be multiple data in a component
  • Get the status through this.state
//Basic use of state

class Opp extends React.Component {
	// constructor() {
	// 	super()
	// 	//Initialization
	// 	this.state = {
	// 		count: 0
	// 	}
	// }

	// Simplify syntax initialization state
	state = {
		count: 0
	}
	render() {
		return (
			<div>
				<h1>Counter:{this.state.count}</h1>
			</div>
		)
	}
}

4.5.2 setState() modification status

  • The state is variable

  • this.setState({data to modify})

  • Do not modify the value in state directly

  • steState() function: 1. Modify state 2. Update UI

    class Opp extends React.Component {
    	state = {
    		count: 0
    	}
    	render() {
    		return (
    			<div>
    				<h1>Counter:{this.state.count}</h1>
    				<button
    					onClick={() => {
    						this.setState({
    							count: this.state.count + 1
    						})
    					}}
    				>
    					+1
    				</button>
    			</div>
    		)
    	}
    }
    

4.5.3 extracting event handlers from JSX (code optimization)

Separate the logic into a separate method to ensure that the JSX structure is clear

class Opp extends React.Component {
	state = {
		count: 0,
	}

	// Event handler
	onIncrement() {
		this.setState({
			count: this.state.count + 1
		})
	}

	render() {
		return (
			<div>
				<h1>Counter:{this.state.count}</h1>
				<button onClick={(this, this.onIncrement)}>+1</button>
			</div>
		)
	}
}

Error reporting: the extracted this is undefined, which will be solved in the next section

4.6 event binding this point

4.6.1 arrow function

The arrow function itself does not bind this. This in the lander () method is a component instance, and you can get setState()

	render() {
		return (
			<div>
				<h1>Counter:{this.state.count}</h1>
				<button onClick={() => this.onIncrement()}>+1</button>
			</div>
		)
	}

4.6.2 Function.prototype.bind()

Use the bind method in ES5 to bind this in the event handler with the component instance

class Opp extends React.Component {
	constructor() {
		super()

		state = {
			count: 0,
		}
		this.onIncrement = this.onIncrement.bind(this)
	}

	// Event handler
	onIncrement() {
		this.setState({
			count: this.state.count + 1,
		})
	}

	render() {
		return (
			<div>
				<h1>Counter:{this.state.count}</h1>
				<button onClick={this.onIncrement}>+1</button>
			</div>
		)
	}
}

4.6.3 instance method of class (recommended)

class instance method in the form of arrow function

class Opp extends React.Component {
	state = {
		count: 0
	}
	// Event handler
	onIncrement = () => {
		this.setState({
			count: this.state.count + 1
		})
	}

	render() {
		return (
			<div>
				<h1>Counter:{this.state.count}</h1>
				<button onClick={this.onIncrement}>+1</button>
			</div>
		)
	}
}

4.7 form processing

4.7.1 controlled components

A form element whose value in a mutable state is controlled by React

React binds the state and the value of the form element together, and the value of the form element is controlled by the state value

  1. Add a state in state as the value value of the form element (which controls the source of the form element value)
  2. Bind the change event to the form element and set the value of the form element to the value of state (control the change of the value of the form element)
// Controlled component that controls the value of the text box

class Opp extends React.Component {
	state = {
		txt: "",
	}

	handleChange = (e) => {
		this.setState({
			txt: e.target.value
		})
	}

	render() {
		return (
			<div>
				<input
					type='text'
					value={this.state.txt}
					onChange={this.handleChange}
				/>
			</div>
		)
	}
}

4.7.2 multi form element processing (code optimization)

  1. Add a name attribute to the form element with the same name as state

  2. Get the corresponding value according to the form element type

  3. Modify the corresponding state through [name] in the change event handler

    import React from "react"
    import ReactDOM from "react-dom"
    
    // Controlled component that controls the value of the text box
    
    class Opp extends React.Component {
    	state = {
    		txt: "",
    		content: "",
    		city: "bj",
    		isChecked: false,
    	}
    
    	handleForm = (e) => {
    		// Gets the current DOM object
    		const target = e.target
    
    		// Get value by type
    		const value = target.type === "checkbox" ? target.checked : target.value
    
    		// Get name
    		const name = target.name
    
    		this.setState({
    			[name]: value,
    		})
    	}
    
    	render() {
    		return (
    			<div>
    				{/* Text box */}
    				<input
    					type='text'
    					name='txt'
    					value={this.state.txt}
    					onChange={this.handleForm}
    				/>
    				<br />
    				{/* Rich text box */}
    				<textarea
    					name='content'
    					value={this.state.content}
    					onChange={this.handleForm}
    				></textarea>
    				<br />
    				{/* Drop down box */}
    				<select
    					name='city'
    					value={this.state.city}
    					onChange={this.handleForm}
    				>
    					<option value='bj'>Beijing</option>
    					<option value='sh'>Shanghai</option>
    					<option value='cs'>Changsha</option>
    				</select>
    				<br />
    				{/* check box */}
    				<input
    					name='isChecked'
    					type='checkbox'
    					checked={this.state.isChecked}
    					onChange={this.handleForm}
    				></input>
    			</div>
    		)
    	}
    }
    ReactDOM.render(<Opp />, document.getElementById("root"))
    
    

4.7.3 understanding of uncontrolled components (DOM mode)

With the help of ref, use the native DOM method to obtain the form element value

ref function: get DOM or component

  1. Call the React.createRef() method to create a ref object
  2. Add the created ref object to the text box
  3. Get the value of the text box through the ref object
import React from "react"
import ReactDOM from "react-dom"

// Uncontrolled components

class Opp extends React.Component {
	constructor() {
		super()

		// Create ref
		this.txtRef = React.createRef()
	}

	// Gets the value of the text box
	getTxt = () => {
		console.log("The value of the text box is:", this.txtRef.current.value)
	}

	render() {
		return (
			<div>
				<input type='text' ref={this.txtRef} />
				<button onClick={this.getTxt}>The value of the text box</button>
			</div>
		)
	}
}
ReactDOM.render(<Opp />, document.getElementById("root"))

summary

Today I learned the following:
React component Foundation
1. There are two ways to create components: function components and class components
2. Stateless (function) component, responsible for static structure display
3. The stateful (class) component is responsible for updating the UI and making the page move
4. When binding events, pay attention to the problem of this pointing
5. It is recommended to use controlled components to process forms

Posted by sanchez77 on Tue, 05 Oct 2021 10:48:10 -0700