1, Component introduction
Component is the core of react. Using react means using components.
Component represents some functions in the page, and multiple components are combined to achieve complete page functions. It is characterized by reusability, independence and combination.
React component can cut the UI into some independent and reusable parts, which helps designers focus on building each individual part.
2, Two ways to create components
1. Creating components using functions
- Function component: a component created using JS functions (or arrow functions)
- Convention 1: the function name must start with a capital letter, and React distinguishes between components and ordinary React elements
- Convention 2: a function component must have a return value indicating the structure of the component
- If the return value is null, nothing will be rendered.
- Render function component: use the function name as the component label name.
//1. Import import React from 'react'; import ReactDOM from 'react-dom' //2. Create function component function Hello(){ return( <div>First function component</div> ) } //Components created using arrow functions const Hello = ()=><div>First function component</div> //3. Rendering components ReactDOM.render(<Hello />,document.getElementById('root'))
2. Creating components using classes
- Class component: create a component using the class of ES6
- Convention 1: class names must also start with uppercase letters.
- Convention 2: class components should inherit the parent class of React.Component so that they can use the methods or properties provided in the parent class.
- Convention 3: a class component must provide a render() method.
- Convention 4: the render() method must have a return value indicating the structure of the component.
import React from 'react'; import ReactDOM from 'react-dom' //Create class component class Hello extends React.Component { render() { return ( <div>This is my first class component</div> ) } } //Rendering Components ReactDOM.render(<Hello />,document.getElementById('root'))
3. Extract as a separate JS file
After there are many project components, it is recommended that each component be placed in a separate js file as an independent individual.
- Create Hello.js
- Import React in Hello.js
- Create a component (function or class)
- Export the component in Hello.js
- Import the Hello component in index.js
- Rendering Components
//Hello.js import React from 'react'; //Create component class Hello extends React.Component { render (){ return ( <div>This is my first time to pull away js Components in file</div> ) } } // Export components export default Hello; //index.js import React from 'react'; import ReactDOM from 'react-dom' import Hello from './Hello' ReactDOM.render(<Hello />,document.getElementById('root'))
3, React event handling
1. Event binding
- The React event binding syntax is similar to the DOM event syntax
Syntax: on + event name = {event handler},
For example, click event: onclick = {() = > {}}
Note: the React event adopts the hump naming method, such as onMouseEnter and onFous
import React from 'react'; import ReactDOM from 'react-dom' class APP extends React.Component{ //Event handler handleClick() { console.log('Click event triggered') } render(){ return( <button onClick={this.handleClick}>Point me point me</button> ) } } //Binding events in function components function APP() { function handleClick() { console.log('Click event triggered') } return ( <button onClick={handleClick}>Point me</button> ) } ReactDOM.render(<APP />,document.getElementById('root'))
2. Event object
- The event object can be obtained from the parameters of the event handler
- Event objects in React are called composite events (objects)
- Composite events: compatible with all browsers without worrying about cross browser compatibility
//Click the a tab page of the React event object without jumping to prevent the default behavior of the browser import React from 'react'; import ReactDOM from 'react-dom' class APP extends React.Component { handleClick(e) { //Block browser default behavior with event objects e.preventDefault(); console.log('a The click event of the tag triggered') } render(){ return( <a href="http://Baidu. Com "onclick = {this. Handleclick} > Baidu</a> ) } } ReactDOM.render(<APP />,document.getElementById('root'))
4, Stateful and stateless components
- Function components are also called stateless components, and class components are called stateful components
- state is data.
- The function component does not have its own state and is only responsible for data display (static)
- Class components have their own state and are responsible for updating the UI and making the page move
5, state and setstate in the component (make the component move)
1. Basic use of state
state, that is, data, is the 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 status: this.state
/*state Basic use of Counter case */ import React from 'react'; import ReactDOM from 'react-dom' class APP extends React.Component { /* constructor(){ super() // Initialize state this.state = { count:0 } } */ // Simplify syntax initialization state state = { count:0 } render() { return( <div> <h1>Stateful component--Calculator :{this.state.count}</h1> //{this.state.count}: use state </div> ) } } ReactDOM.render(<APP />,document.getElementById('root'))
effect:
2. setState() modify state
- The state is variable
- Syntax: this.setState({data to modify})
- Note: do not directly modify the value in state, which is wrong!!!
- setState() function: 1. Modify state 2. Update UI
- Idea: data driven view
import React from 'react' import ReactDOM from 'react-dom' /* state Basic use of */ class APP extends React.Component { state = { count:0, test:'a' //It is used to compare tests. When modifying in setstate, you don't need to put both in for modification } render(){ return( <div> <h1>Counter:{this.state.count}</h1> <button onClick={()=>{ this.setState({ count:this.state.count + 1 //Add 1 to the current state to realize the function of counter }) /* Error demonstration!!! this.state.count += 1 */ } }>+1</button> </div> ) } } //Rendering Components ReactDOM.render(<APP />,document.getElementById('root'))
//correct this.setState({ count:this.state.count+1 }) //error this.state.count += 1
effect:
Click plus 1 to change the counter
3. Pull the event handler (optimization) from JSX, and this pointing problem occurs
- JSX is mixed with too much JS logic code, which will be very chaotic (JSX's own function is to describe the page structure, so too much JS code will affect the programmer's feeling of reading code)
- Recommendation: separate the logic into a separate method to ensure that the JSX structure is clear
class APP extends React.Component { state = { count:0, } //Event handler onIncrement() { this.setState({ //The value of this is undefined count:this.state.count + 1 }) } render(){ return( <div> <h1>Counter:{this.state.count}</h1> <button onClick={this.onIncrement}>+1</button> </div> ) } } //Rendering Components ReactDOM.render(<APP />,document.getElementById('root'))
Error reported. Reason: the value of this in the event handler is undefined
Hope: this points to the component instance (this in the render method is the component instance)
6, Event binding this point (solve the problem just now)
1. Using arrow function to solve
- Using the feature that the arrow function itself does not bind this
- this in the render() method is a component instance, and you can get setState()
class APP 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> //this in the arrow function points to the external environment. Here is the render() method <button onClick={()=>{this.onIncrement()}}>+1</button> </div> ) }
Taking advantage of the fact that the arrow function itself does not bind this, this in the arrow function points to the render component instance. This is also this in the event handler, so it is the same this. At this time, the program can run successfully.
2,Function.prototype.bind()
- Use the bind () method in ES5 to bind this in the event handler with the component instance
class APP extends React.Component { constructor (){ super() this.state = { count:0, } this.onIncrement = this.onIncrement.bind(this) } //Event handler onIncrement() { console.log('In the event handler this: ',this) this.setState({ count:this.state.count + 1 }) } render(){ return( <div> <h1>Counter:{this.state.count}</h1> <button onClick={this.onIncrement}>+1</button> </div> ) } }
3. class instance method
class instance method in the form of arrow function
Note: this syntax is experimental, but it can be used directly due to the existence of babel
class APP extends React.Component { state = { count:0, } //Event handler onIncrement=()=>{ console.log('In the event handler this:',this) this.setState({ count:this.state.count+1 }) } render() { return( <div> <h1>Counter:{this.state.count}</h1> <button onClick={this.onIncrement}>+1</button> </div> ) } }