Hello World
The simplest code example is as follows
ReactDOM.render(<h1>Hello world</h1>.document.getElementById('root'))
Copy the code
What is the JSX
concept
JSX is a syntactic extension of javascript, commonly used with React to describe the look and feel of the UI. JSX has all the functionality of javascript.
A simple example
This is a simple JSX example
const element = <h1>Hello world</h1>
Copy the code
Is equivalent to
const element = React.createElement(
'h1',
{className: 'greeting'},
'Hello, world! '
);
Copy the code
Why JSX
React is essentially a renderer, implemented by loosely coupling markup to logic components. React doesn’t require JSX. You can also use react. React also allows you to display more useful errors and warnings.
Complex sample
JSX is compiled to become a regular javascript function call, which means that if you use function methods, you can use if statements and for loops to handle variables in JSX, and you can embed expressions, specify properties, bind events, and so on
const formatName = (user) = > {
return user.name1 + ' ' + user.name2
}
const buttonClick = (e) = > {
alert(e)
}
const user = {
name1: 'name1'.name2: 'name2',}const buttonType = "button"
const element = (
<button
type={buttonType}
onClick={buttonClick}
>
Hello, {formatName(user)}
</button>
)
ReactDOM.render(element, document.getElementById('root'))
Copy the code
Advanced sample
This is shown in the example below
- The binding event
- Using expressions
- Through the data
- Nested structure
- The embedded variable
- Set properties
// Use expressions
const formatName = (user) = > {
return user.name1 + ' ' + user.name2
}
// Bind events
const buttonClick = (e) = > {
alert(e)
}
// Iterate over the data
const list = ['list1'.'list2'.'list3'.'list4']
const renderList = (list) = > {
return list.map((item,index) = >{
return <span key={index}>{item}</span>})}// Button content
const user = {
name1: 'name1'.name2: 'name2',}// Button color
const color = '#ccc'
// Set the properties
const buttonType = "button"
const element = (
<div>
{renderList(list)}
<button/ / setcss
style={{'color': color}} // Set the propertiestype={buttonType}// Bind eventsonClick={buttonClick}
>
Hello, {formatName(user)}
</button>
</div>
)
ReactDOM.render(element, document.getElementById('root'))
Copy the code
Of course, the examples above are simple examples, and there are more complex examples to follow
component
concept
Components are like javascript functions in that they accept arbitrary inputs (props) and return react elements that describe what should be displayed on the screen
Note that components need to start with a capital letter
There are two types of components in React, one is functional component and the other is class component
Functional component
Functional components have the following features:
- No state of its own
- Return an element
- No life cycle
All function components in React must be pure functions that do not change their properties
function Welcome(props){
return <h1>Hello, {props.name}</h1>
}
Copy the code
Class components
Class components have the following features:
- Declare components in es6 class mode
- You need to inherit react.componentto use the React lifecycle
- There is a declaration period
- Self stateful
- The component can be updated by calling the setState method
- The render function retur an element to render
class Welcom extends React.Component {
render(){
return <h1>Hello, {this.props.name}</h1>}}Copy the code
The sample
Not only HTML tags are available in JSX, but our declared components are also available
function Welcome(props){
return <h1>Hello, {props.name}</h1>
}
const element = <Welcome name="name1" />
ReactDOM.render(
element,
document.getElementById('root'))Copy the code
Complex sample
Components can be reused, they can be nested, we can use the same structure or a function of the package into a component, do not be afraid to break components into smaller components
function Nav (props){
return (
<div className="nav">
<img src={props.logo} alt="logo" />
<ul>
<li><a href={props.nav[0].href}>{props.nav[0].name}</a></li>
<li><a href={props.nav[1].href}>{props.nav[1].name}</a></li>
<li><a href={props.nav[2].href}>{props.nav[2].name}</a></li>
<li><a href={props.nav[3].href}>{props.nav[3].name}</a></li>
</ul>
<div className="user">
<img src={props.user.pic} alt="user" />
<span>{props.user.name}</span>
</div>
</div>)}const element = (
<div className="nav-warp">
<Nav logo="" nav={} [] user={{pic:"',name:"'}} / >
</div>
)
ReactDOM.render(
element,
document.getElementById('root'))Copy the code
Above is the structure of a navigation bar, which we can subdivide
function Logo(props) {
return <img src={props.logo} alt="logo" />
}
function NavList(props) {
return (
<ul>
{props.nav.map((item, index) => {
return (
<li key={index}><a href={item.href}>{item.name}</a></li>)})}</ul>)}function User(props) {
return (
<div className="user">
<img src={props.user.pic} alt="user" />
<span>{props.user.name}</span>
</div>)}function Nav(props){
return (
<div className="nav">
<Logo logo="" />
<NavList nav={} [] />
<User user={{pic:"',name:"'}} / >
</div>)}const element = (
<div className="nav-warp">
<Nav />
</div>
)
ReactDOM.render(
element,
document.getElementById('root'))Copy the code
State and life cycle
Components declared in ES6’s class that inherit react.componenthave their own state and life cycle
state && setState
State refers to the state of the component itself
Using state to control component changes can treat a component as a state machine, with each state corresponding to one UI of the component
Note that setState is an asynchronous function and does not take effect immediately
import React, { Component } from 'react'; class StateDemo extends Component { state = { secondsElapsed: 0 } tick(){ this.setState({ secondsElapsed: this.state.secondsElapsed + 1 }); } componentDidMount(){ this.interval = setInterval( this.tick.bind(this), 1000 ); } componentWillUnmount(){ clearInterval(this.interval); } to render () {return (< div > has been timing: {this. State. SecondsElapsed} seconds < / div >)}} export default StateDemo;Copy the code
props
Props refers to the state that the parent component passes to the child component
This. Props can be used to get the properties passed to the component. GetDefaultProps can also be used to specify the default properties. This.props. Children this. Props. Map this
import React, { Component } from 'react'; Class PropsDemo extends Component {props = {title: 'This is the default title property value'} render(){console.log(this.props); return <b>{this.props.title}</b> } } export default PropsDemo; // <PropsDemo title=" set title "/>Copy the code
Function component updates the page
To update the state without using a life cycle we can only do this by constantly executing the reactdom.render function
var count = 0
function buttonClick() {
count = count + 1
render()
}
const render = () = > {
const element = (
<div className="warp">
<div>Click {count} times</div>
<button type="button" onClick={buttonClick}>Click on the</button>
</div>
)
ReactDOM.render(
element,
document.getElementById('root')
)
}
render()
Copy the code
Class component updates state
The internal component can update the state by calling the setState function to update the page
class App extends React.Component {
state = {
count: 0
}
buttonClick = () = > {
this.setState({
count: this.state.count + 1})}render() {
alert(this.state.count)
return (
<div className="warp">
<div>Hit {this.state.count} times</div>
<button type="button" onClick={this.buttonClick}>Click on the</button>
</div>
)
}
}
ReactDOM.render(
<App />.document.getElementById('root'))Copy the code
The life cycle
In the above link, we use function components and component class implements a counter components, used to render and setState, in practice, we need to have updated detailed control to the state of the components, the component performance optimization, and achieve more demand, this time you need to use the react function of life cycle
There’s a lot of space below, so if you want to see the life cycle diagram, scroll down
The React lifecycle consists of three phases: initialization, in-operation, and destruction.
Initialization phase
getDefaultProps()
Set the default properties of the component. You can set the defaultProps with static defaultProps
getInitialState()
Es6 class syntax does not use this hook function; use constructor instead;
A React Component needs to inherit the React Component base class to have render(), lifecycle, and other methods available, which is why function components cannot use them; The super(props) constructor is used to call the constructor of the base class and inject the props of the parent component into the child component for the child component to read. Constructor () is used to initialize components, such as defining the initial content of this.state and binding functions with the bing() method so that this points to the current class so that all methods of that class can be accessed from the function;
ComponentWillMount () React 16.7
Triggered just before the component is about to be rendered to the page; Calling this.setState() does not trigger render because componentWillMount() will be removed, so it is officially recommended to use constructor() instead
render()
When the component is rendered to the page, you can start the timer and send a request to the server, etc. The parent component needs to render again. Changes in props and state will render again, and you need to return a result
componentDidMount()
Trigger when the component has been rendered to the page; It will only be called once; The page now has a real DOM element and can perform DOM related operations; [Fixed] Server side rendering will not be triggered
In-operation phase
componentWillReceiveProps()
Emitted when the component receives a property; React 16.7 was replaced by static getDerivedStateFromProps()
shouldComponentUpdate()
React performance tuning is an important part of the process. If the props and state are the same, return false to block the update, because the same property state must generate the same DOM tree. In this way, there is no need to create a new DOM tree to compare the old DOM tree with the diff algorithm, which saves a lot of performance, especially when the DOM structure is complex
The update of a parent component causes all of its children to re-execute the render() method to form a new virtual DOM, and the diff algorithm is used to compare the structure and properties of the old and new virtual DOM to determine whether the component needs to be re-rendered.
React, for example, provides a PureComponent class. When our component inherits from it, the component updates by default by comparing the new and old properties and states to determine whether the component is updated. It’s worth noting that PureComponent makes shallow comparisons, so it needs to return a new object or array whenever component state or properties change
Common use cases include setting variables based on state changes, dispatching events, and starting animations
componentWillUpdate()
Triggered when a component is about to be updated; Replaced by getSnapshotBeforeUpdate() in React 16.7
Called after render, when DOM can be read but cannot be used. You can capture some information (such as scroll position) from the DOM before possible changes. Any value returned by this life cycle is passed as the third argument to componentDidUpdate().
componentDidUpdate()
Triggered when the component has been updated. A new DOM element is generated in the page, and DOM manipulation can be performed with two parameters, namely props and state before the update
Destruction of phase
componentWillUnmount()
Triggered when a component is destroyed. Here we can do some cleanup, unsubscribe Redux events, remove event listeners added to componentDidMount or elsewhere, disconnect network requests, empty timers, and clean up DOM elements created in componentDidMount
The whole process is shown below
16.7 before
After 16.7
You can add 885356143 to the React front-end group