Introduction to React components
- The component is a first-class citizen of React. Using React means using the component
- Component represents some functions in a page
- Combine multiple components to achieve complete page functions
- Features: reusable, independent and composable
How components are created
1. Function creation component
- Function component: use JS functions to create components
- Function names must start with uppercase letters
- 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
Writing function components
function Hello() { return ( <div>This is the first function component</div> ) }
Rendering with ReactDOM.render()
ReactDOM.render(<Hello />,document.getElementById('root'))
2. Class components
- Components created using class of ES6 syntax
- Class names must also begin with an uppercase letter
- Class components should inherit the React.Component parent class so that they can use the methods or properties provided in the parent class
- Class component must provide render method
- The render method must have a return value
- Create a class class, inherit React.Component, provide render method in it, and return content in return
class Hello extends React.Component{ render(){ return ( <div>This is the first class component</div> ) } }
- Rendering through ReactDOM
ReactDOM.render(<Hello />,document.getElementById('root'))
Extract into separate JS files
As an independent individual, components are generally placed in a separate JS file
- Create JS file
- Import React in js file, create components, and export them in js file
// Hello.js import React from 'react' export default class extends React.Component { render(){ return ( <div>Pulled out alone Hello</div> ) } }
- Import the Hello component in index.js and render it to the page
// index.js import Hello from './js/Hello' ReactDOM.render(<Hello />,document.getElementById('root'))
React event handling
Event binding
- The React event binding syntax is similar to the DOM event syntax
- Syntax: on + event name = event handling function, such as onClick = function() {}
- Note: the React event adopts the hump naming method
export default class extends React.Component { clickHandle(e){ console.log('Yes') } render(){ return ( <div><button onClick = {this.clickHandle}>Point me point me point me</button></div> ) } }
Summary
- Binding events in React is very similar to native events
- It should be noted that in the React binding event, the hump naming method should be followed
- The event binding of class components is similar to that of function components, but this is required when binding event functions in class components, which represents a reference to the current class. This does not need to be called in the function
Event object
- You can get the event object through the parameters of the event handler function
- The event object in React is called a composite event
- Composite event: compatible with all browsers without worrying about cross browser compatibility
- In addition to being compatible with all browsers, it also has the same interface as browser native events, including stopPropagation() and preventDefault()
- If you want to get the native event object, you can get it through the nativeEvent property
export default class extends React.Component { clickHandle(e){ // Get native event object console.log(e.nativeEvent) } render(){ return ( <div><button onClick = {this.clickHandle}>Point me point me</button></div> ) } }
Supported events
-
Clipboard Events clipboard events
- Event name: onCopy, onCut, onPaste
- Property: domdatatransfer clipboard data
-
compositionEvent composite event
- Event name: onCompositionEnd, onCompositionStart, onCompositionUpdate
- Attribute: string data
-
Keyboard Events
- Event name: onKeyDown, onKeyPress, onKeyUp
- Attribute: for example, number keyCode
-
Focus Events (these Focus Events are valid for all elements on the React DOM, not just form elements)
- Event name: onFocus, onBlur
- Property: DOMEventTarget relatedTarget
-
Form Events
- Event name: onChange, onInput, onInvalid, onSubmit
...
Stateful and stateless components
- Function components are also called stateless components, and class components are also called stateful components
- State is data
- The function component does not have its own state and is only responsible for data display
- Class components have their own state and are responsible for updating the UI and making the page move
State and SetState
state basic usage
- 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 the status through this.state
export default class extends React.Component { constructor(){ super() // The first initialization method this.state = { count : 0 } } // The second initialization method state = { count:1 } render(){ return ( <div>Counter :{this.state.count}</div> ) } }
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
export default class extends React.Component { // The second initialization method state = { count:1 } render(){ return ( <div> <div>Counter :{this.state.count}</div> <button onClick={() => { this.setState({ count: this.state.count+1 }) }}>+1</button> </div> ) } }
Summary
- To modify the value in state, we need to modify it through this.setState()
- There will be listening at the bottom of React. Once we call setState and the data changes, we will call the render method again to re render the current component
Extract event handler
- When we extract the event handler of the above code, an error will be reported and this cannot be found
reason
- This can be found in the event handling function we wrote in JSX. The reason is that in JSX, we use the arrow function. The arrow function does not bind this, so it will look for the outer layer. The outer layer is the render method. This in the render method just points to the current instance object
Event binding this point
Arrow function
- Using the feature that the arrow function itself does not bind this
Using the bind method (★★★)
The prototype bind method can change the direction of this in the function, so we can call the bind method in the construction and assign the returned value to our function.
class App extends React.Component { constructor() { super() ... // The direction of this in the current function is changed through the bind method this.onIncrement = this.onIncrement.bind(this) } // Event handler onIncrement() { ... } render() { ... } }
class instance method
- class instance method in the form of arrow function
- Note: this syntax is experimental, but it can be used due to the existence of babel
// Event handler onIncrement = () => { console.log('In the event handler this: ', this) this.setState({ count: this.state.count + 1 }) }
Recommendation: using the instance method of class is also the reason why the dependent arrow function does not bind this