Introduction of the React
First of all, it cannot be denied that React. Js is the most popular front-end framework in the world (the front-end framework launched by Facebook). Most first-tier and second-tier Internet companies in China use React for development, such as Ali, Meituan, Baidu, Qunar, netease, Zhihu and other first-tier Internet companies regard React as the main front-end technology stack.
The React community is also very strong, with more useful frameworks such as ReactNative and React VR growing in popularity. React has been promoted since 2013, and now the React Fiber (16RC) version has been released, which has greatly improved performance and ease of use.
React Advantages
- The Ecosystem is strong: No framework is better than the React ecosystem, with mature solutions for almost all development needs.
- Easy to get started: You can even get the React technology up and running in a few hours, but its knowledge is so extensive that you may need more time to fully navigate it.
- Strong community: You can easily find like-minded people to study with because there are so many people using it.
Required prior knowledge
-
JavaScript Basics: ES6 is even better
-
NPM basics: You need package management that knows how to use NPM
React development environment setup
- To install Node, simply go to the Node website, download the response version, and double-click install.
// The installation is complete. Open the command window and enter node -v. If the version number is displayed, the installation is successfulCopy the code
- Erection of scaffolding
NPM install -g create-react-app install -g create-react-app install -g create-react-app install -g create-react-app install -g create-react-app install -g create-react-appCopy the code
- Create a React project
Create the react project with scaffolding NPM start // Install the react project in the demo folderCopy the code
Introduction of files in the project root directory
-
Readme.md: This file is a description of the project, and it’s already written by default, so you can look at it briefly. If you are working, you can delete the contents of the file and write the file yourself. You can write the file using Markdown syntax.
-
Package. json: This file is the WebPack configuration and project package management file, the third-party packages (package version) and some common command configuration are configured in this file. Of course, scaffolding has configured some for us, so we don’t need to change the current position. If you’re familiar with WebPack, you’ll be familiar with this.
-
Package-lock. json: this is a file that locks the install version number and needs to be uploaded to Git to ensure that everyone else has the same dependencies when installing NPM.
-
Gitignore: This is a git optional upload configuration file, such as the node_modules folder, which will be introduced later.
-
Node_modules: This folder is our dependency package for the project, so far the scaffolding has been downloaded, you don’t need to install anything separately.
-
Public: a public file that contains common templates, ICONS, etc.
-
SRC: Main code writing files, the files in this folder are the most important for us to know.
Public Folder introduction
This file is a common file used by some projects, that is, it is shared
-
Favicon. ico: This is the icon of a website or project, usually displayed in the upper left corner of a browser TAB.
-
Index.html: template file for the home page
-
Mainifest. Json: mobile configuration file
SRC folder introduction
This directory is our open source code, we usually do the most operations directory.
-
Index.js: This is the entry file for the project
-
Index.css: This is the CSS file in index.js.
-
App.js: This file is equivalent to a method module, which is also a simple modular programming.
-
Serviceworker.js: This file is used to write mobile applications. PWA must use this file, which is equivalent to offline browsing.
Component Introduction
Entry file preparation
The index.js file in the SRC directory is the entry file used to write a project
import React from 'react'// React import ReactDOM from'react-dom'// React-dom import App from'./App'// reactdom.render (<App />, document.getelementbyid ('root'// Render the App module to the root IDCopy the code
Writing of App components
import React from 'react'// JSX extends React.Component{render() {return<div> I am APP component </div>}}export default App;
Copy the code
React JSX syntax introduction
JSX is a combination of Javascript and XML. React invented JSX, which makes it easy to create a virtual DOM using HTML syntax. When encountered with <, JSX interprets it as HTML and when encountered with {it interprets it as JavaScript.Copy the code
Component and normal JSX syntax differences
This is a simple sentence: your custom components must start with a uppercase letter, and JSX starts with a lowercase letter.
Ternary operators are used in JSX
Js syntax is also available in JSX
import React from 'react'// JSX extends React.Component{render() {return (
<div>
<div>{false ? 'Don't show me' : 'Show me'</div> I am APP component </div>)}}export default App;
Copy the code
Component outer wrapping principle
React follows the same principle as vue component templates: There must be only one element in the outermost layer
The following column is an error because there are two elements in the outermost layer
import React from 'react'// JSX extends React.Component{render() {return (
<div></div>
<div>
<div>{false ? 'Don't show me' : 'Show me'</div> I am APP component </div>)}}export default App;
Copy the code
Fragments label
Add the outermost DIV and the component is perfectly normal, but your layout doesn’t need the outermost tag. For example, when we do Flex layout, we really can’t have wrap elements around it. This contradiction has already been taken into account by React16, which has prepared labels for us.
import React from 'react'// JSX extends React.Component{render() {return (
<React.Fragment>
<div>{false ? 'Don't show me' : 'Show me'}</div>
</React.Fragment>
)
}
}
export default App;
Copy the code
If you check Elements in your browser, you’ll see that there are no more outer wraps.
Responsive design and binding of data
React doesn’t recommend manipulating DOM elements directly, but rather using data to drive changes in the interface. React automatically changes the interface based on data changes. So when you write React code, you don’t need to focus on the DOM, you just need to focus on the data. (This is why React is so popular, and it speeds things up a lot.)
import React from 'react'{constructor(props){super(props)} // This. State ={myName: // this.'Just tomato and eggs.',
list: ['tomato'.'scrambled egg']}}render() {return (
<React.Fragment>
<div>{this.state.myName}</div>
<ul>
{
this.state.list.map((item,index) => {
return (
<li key={item + index}>{item}</li>
)
})
}
</ul>
</React.Fragment>
)
}
}
export default App;
Copy the code
The binding event
import React from 'react'{constructor(props){super(props)} // This. State ={myName: // this.'Just tomato and eggs.',
list: ['tomato'.'scrambled egg']
}
this.changeBtn = this.changeBtn.bind(this)
}
render() {return< react. Fragment> <div>{this.state.myName}</div> <button onClick={this.changebtn}> </button> </ react. Fragment>}changeBtn() {// this is undefined if this is not boundsetState method to change the data to ensure that the page will render the content of the change after this. SetState ({myName:'My value changed after I clicked the button'}}})export default App;
Copy the code
JSX anti-tread pit several places
JSX code comments
There are two ways to write code comments
{/ * correct written comment * /} {/ / correct written comment}Copy the code
Class traps in JSX
It is used to prevent conflicts with the js class name, so JSX uses className
<input class="input"<input className= /> //"input"/> < span style = "max-width: 100%Copy the code
HTML parsing problems in JSX
If you want to enter an H1 tag in the text box and render it. The default won’t work and will just print the H1 tags to the page, which is not what I want. If you have this requirement at work, you can use the dangerouslySetInnerHTML attribute to resolve it. The specific code is as follows:
<li dangerouslySetInnerHTML={{__html:item}}> {<h1> I will become h1 font </h1>}</li>Copy the code
JSX tag pit
JSX label pit, also a relatively large pit, label is an HTML auxiliary label, is also a very useful label.
<div> <label> joins the service: </label> <input className="input"Value ={this.state.inputValue} onChange={this.inputchange.bind (this)} /> <button onClick={this.addlist.bind (this)}> Add service </button> </div>Copy the code
Click “Join service” to activate the text box for easy input. The original idea of HTML is to just add the ID. The code is as follows:
<div>
<label for="jspang"> Add service: </label> <input ID ="jspang" className="input"Value ={this.state.inputValue} onChange={this.inputchange.bind (this)} /> <button onClick={this.addlist.bind (this)}> Add service </button> </div>Copy the code
You can browse normally, but there is still a red warning on the console. You can’t use for. It can be confused with the for loop in javascript, which prompts you to use HTMLfor.
<div>
<label htmlFor="jspang"> Add service: </label> <input ID ="jspang" className="input"Value ={this.state.inputValue} onChange={this.inputchange.bind (this)} /> <button onClick={this.addlist.bind (this)}> Add service </button> </div>Copy the code
Component splitting
How does the parent use the child
// Subcomponent import React from'react'Class childItem extends React.Component{return< react. Fragment> <div> I am a child </div> </ react. Fragment>}export default childItem;
Copy the code
// The parent component import React from'react'// Import childItem from'./childItem'Class parentItem extends React.Component{return(< react. Fragment> {/* uses child components */} <childItem/> </ react. Fragment>)}export default parentItem;
Copy the code
The parent component passes values
The parent component passes a value to the child through a custom property
// The parent component import React from'react'// Import childItem from'./childItem'// JSX syntax class parentItem extends React.Component{constractor (props) {super(props) this.state = {myName:'Just tomato and eggs.'}}return(< react. Fragment> {/* uses child components */} <childItem myName={this.state.myName}/> </ react. Fragment>)}export default parentItem;
Copy the code
The child component accepts the value returned from the parent component via this.props.XXX
// Subcomponent import React from'react'Class childItem extends React.Component{return (
<React.Fragment>
<div>{this.props.myName}</div>
</React.Fragment>
)
}
export default childItem;
Copy the code
The parent component passes content to the child, in the form of properties.
The child component passes data to the parent
Remember single data stream!!
React explicitly states that child components cannot manipulate data in the parent component. Therefore, use a parent component’s method to modify the content of the parent component.
// Subcomponent import React from'react'// JSX syntax class childItem extends React.Component{constructor (props) {super(props) this.changeparent = this.changeParent.bind(this) }return (
<React.Fragment>
<div onClick={this.changeParent}>{this.props.myName}</div>
</React.Fragment>
)
changeParent() {// call the method passed by the parent component this.props. PranentChange ()}}export default childItem;
Copy the code
// The parent component import React from'react'// Import childItem from'./childItem'// JSX syntax class parentItem extends React.Component{constractor (props) {super(props) this.state = {myName:'Just tomato and eggs.'
}
this.pranentChange = this.pranentChange.bind(this)
}
return(< react. Fragment> {/* use child component */} <childItem pranentChange={this.pranentchange} myName={this.state.myname} /> </React.Fragment> )pranentChange () {
this.setState({
myName: 'Tomato scrambled eggs with less sugar'}}})export default parentItem;
Copy the code
PropTypes verifies passed values
When a parent component passes data to a child component, it uses properties, also known as props, but there are no restrictions. This is not allowed at work, because large projects, if you do not check, will become extremely chaotic later, the business logic can not be guaranteed.
The application of PropTypes
Ordinary efficacy
// Subcomponent import React from'react'// Import PropTypes from'prop-types'// JSX syntax class childItem extends React.Component{constructor (props) {super(props) this.changeparent = this.changeParent.bind(this) }return (
<React.Fragment>
<div onClick={this.changeParent}>{this.props.myName}</div>
</React.Fragment>
)
changeParent() {// call the method passed by the parent this.props. PranentChange ()}} childitem.prorTypes = {myName: PropTypes. String, // The incoming content must be a string pranentChange: PropTypes. Func // The incoming content must be a stringfunction
}
export default childItem;
Copy the code
Note: If you do not pass in the content according to the effect rule, you will get a warning
Validation of required values –isRequired
For example, if you add a newName attribute and put it in JSX, there will be no error even if the parent component does not pass this value
/ / child componentrender() {
return (
<div >{this.props.newName}</div>
);
}
Copy the code
But how do you avoid having to pass the newName attribute value? An error is reported if it is not passed, which requires the isRequired keyword, which indicates that it must be passed, and an error is reported if it is not.
ChildItem. ProrTypes = {/ / efficacy of the incoming content must be and must pass in a string value newName: PropTypes. String. IsRequired,}Copy the code
Use the default value defaultProps
Sometimes a child component needs a default value. If the parent component doesn’t pass the default value, and if the parent component passes the default value,defalutProps can implement the default function. For example, now the default value for newName is “tomato-scrambled eggs”.
Childitem. defaultProps = {// The child uses the values passed by the parent, but it has a default value of its own newName:'Just tomato and eggs.'
}
Copy the code
How to use ref
When writing methods in components, you often encounter code that is semantically ambiguous, which can be a major problem for team development. Reviewing code or collaborating with others can affect development efficiency. Or to this core members leave, the serious impact of the project closure. So we have to pay attention to semantics in react code. Ref is a good tool
import React from 'react'// JSX syntax class parentItem extends React.Component{constractor (props) {super(props) this.state = {myName:'Just tomato and eggs.'
}
this.inputChange = this.inputChange.bind(this)
}
return (
<React.Fragment>
<input
value={this.state.myName}
onChange={this.inputChange}
></input>
</React.Fragment>
)
inputChange (e) {
console.log(e.target.value)
}
}
export default parentItem;
Copy the code
To get the above input value, you have to call e.target.value, which is not intuitive or pretty. Use ref to solve this problem
import React from 'react'// JSX syntax class parentItem extends React.Component{constractor (props) {super(props) this.state = {myName:'Just tomato and eggs.'
}
this.inputChange = this.inputChange.bind(this)
}
return (
<React.Fragment>
<input
value={this.state.myName}
onChange={this.inputChange}
ref={input => {this.input = input}}
></input>
</React.Fragment>
)
inputChange (e) {
console.log(this.input.value)
}
}
export default parentItem;
Copy the code
This makes the code much more semantic and elegant. Refs are not recommended because React is data-driven and can cause problems.
Ref a pit in use
For example, if we want to use the ref binding to get the number of children, we can use the ref binding first.
<ul ref={(ul)=>{this.ul=ul}}>
<li>1</li>
<li>2</li>
<li>3</li>
</ul>
Copy the code
If we add or decrease the number of Li dynamically and print the number of Li in the React method, we find that the number returned is not accurate. The setState has a time in code execution, and if you really want to know, you need to have an understanding of what the virtual DOM is. Simply put, because it is asynchronous, our console.log will be executed before the virtual Dom is rendered.
So what would make this code perfectly normal is that setState actually provides a callback function, which is its second function. So let’s write it this way to get the method we want.
Add/delete (){this.setState({list: changed data,},()=>{console.log(this.ul.querySelectorAll()'li').length)
})
}
Copy the code
The life cycle
What is a lifecycle function
Lifecycle functions are functions that are automatically invoked and executed by the component at some point in timeCopy the code
mount
When a component instance is created and inserted into the DOM, its lifecycle is called in the following order:
- constructor()
If state is not initialized or method binding is not performed, there is no need to implement a constructor for the React component. Before the React component is mounted, its constructor is called. When implementing a constructor for a react.componentsubclass, you should call super(props) before any other statements. Otherwise, this. Props might have undefined bugs in the constructor. In general, constructors in React are used only in two cases: * To initialize internal state by assigning this.state to an object. * Binding instances for event handlers should not be called from the constructor() functionsetThe State () method. If your component needs to use internal state, assign the initial state to this.state directly in the constructor:Copy the code
- static getDerivedStateFromProps()
GetDerivedStateFromProps is called before the Render method is called, and is called both during the initial mount and during subsequent updates. It should return an object to update state, and if null is returned, nothing is updated.Copy the code
- render()
Execute when the page state or props changes.Copy the code
- componentDidMount()
Executed when component mount is complete. This is also where Internet requests are madeCopy the code
update
Updates are triggered when a component’s props or state changes. Component updates are called in the lifecycle order as follows:
- static getDerivedStateFromProps()
// The unusual lifecycle method getDerivedStateFromProps is called before the Render method is called, and is called both during the initial mount and during subsequent updates. It should return an object to update state, and if null is returned, nothing is updated.Copy the code
- shouldComponentUpdate()
// Use shouldComponentUpdate() to determine if the output of the React component is affected by changes to the current state or props. The default behavior is that the component is rerendered every time the state changes. For the most part, you should follow the default behavior.Copy the code
- render()
The Render () method is the only one that must be implemented in the class component. When render is called, it checks for changes to this.props and this.stateCopy the code
- getSnapshotBeforeUpdate()
// The unusual lifecycle method getDerivedStateFromProps is called before the Render method is called, and is called both during the initial mount and during subsequent updates. It should return an object to update state, and if null is returned, nothing is updated.Copy the code
- componentDidUpdate()
ComponentDidUpdate () is called immediately after the update. This method is not performed for the first rendering.Copy the code
uninstall
The following method is called when a component is removed from the DOM:
- componentWillUnmount()
ComponentWillUnmount () is called directly before the component is unmounted and destroyed. Perform necessary cleanup actions in this method, such as clearing timers, canceling network requests, or clearing subscriptions created in componentDidMount().Copy the code
Error handling
When an error is thrown in a rendering process, lifecycle, or child component’s constructor, the following methods are called:
- static getDerivedStateFromError()
This lifecycle is called after a descendant component throws an error. It takes the thrown error as an argument and returns a value to update stateCopy the code
- componentDidCatch()
// The uncommon lifecycle method componentDidCatch() is called in the "commit" phase, thus allowing side effects to be performed. It should be used to log errors and the like:Copy the code
React axios data requests
Install axios
npm install axios -S
Copy the code
use
// That component uses to introduce the import axios from on that page'axios'
Copy the code
I also recommend executing ajax in componentDidMount (render) because there are a lot of issues with executing ajax in Render. Execute in componentWillMount, and when you use RN, you get collisions. So it’s highly recommended to make ajax requests in the componentDidMount function.
componentDidMount(){
axios.post('https://www.easy-mock.com/mock/5d50245e710c4d0d04d78d19/echart')
.then((res)=>{console.log('Axios succeeded in getting data :'+JSON.stringify(res)) })
.catch((error)=>{console.log('Axios fails to get data'+error)})
}
Copy the code
Animation react – the transition – group
React has an excellent development ecosystem. Any basic requirements for development can be found in official or god’s wheels, including animation. There are many third-party animation components in the React ecosystem, so learn about the React – Transition-group animation component. Can meet the daily animation development needs. The most important reason to recommend it is that it is also an official react animation transition library with a well-documented API.
Install the react – the transition – group
npm install react-transition-group -S
Copy the code
Once installed, you can check out the documentation on Github, which has three core libraries (or components).
- Transition
- CSSTransition
- TransitionGroup
Using CSSTransition
Use import to start with the following code:
import { CSSTransition } from 'react-transition-group'
Copy the code
Once introduced, it is ready to use, just as with custom components, written directly, and no longer needs to manage the className, which is managed by CSSTransition.
render() {
return (
<div>
<CSSTransition
in={this.state.isShow} // State used to determine whether or not a state occurs timeout={2000} // animation duration classNames="boss-text"/ / the className value, <div><button onClick={this.totoggole}> </div> </div>); }Copy the code
Note that the classNames attribute belongs to S, so if you forget to write classNames, you will get confused with the original ClassName.
- Xxx-enter: the CSS style before entering.
- Xxx-enter-active: enter the CSS style until the animation is finished;
- Xxx-enter-done: enter the finished CSS style;
- Xxx-exit: CSS style before exit (exit);
- Xxx-exit-active: Exit animation knows the CSS style before completion.
- Xxx-exit-done: CSS style when the exit is complete.
.input {border:3px solid #ae7000}
.boss-text-enter{
opacity: 0;
}
.boss-text-enter-active{
opacity: 1;
transition: opacity 2000ms;
}
.boss-text-enter-done{
opacity: 1;
}
.boss-text-exit{
opacity: 1;
}
.boss-text-exit-active{
opacity: 0;
transition: opacity 2000ms;
}
.boss-text-exit-done{
opacity: 0;
}
Copy the code
UnmountOnExit properties
CSSTransition plus the unmountOnExit attribute means that the DOM is automatically deleted when the element exits, which was previously impossible to do with CSS animation.
render() {
return (
<div>
<CSSTransition
in={this.state.isShow} // State used to determine whether or not a state occurs timeout={2000} // animation duration classNames="boss-text"/ / the className value, <button onClick={this.totoggole}> </button></div> </div> ); }Copy the code
Using TransitionGroup
It is responsible for the animation of multiple DOM elements, let’s take the example of the little sister, now you can add any service items, but all appear directly, no animation, now add animation to it. To add an animation, introduce transitionGrop first.
import {CSSTransition , TransitionGroup} from 'react-transition-group'
Copy the code
Once introduced, you can use this component by adding labels to the outer layer.
<ul ref={(ul)=>{this.ul=ul}}>
<TransitionGroup>
<li>1</li>
<li>2</li>
<li>3</li>
</TransitionGroup>
</ul>
Copy the code
But that’s not enough, you still have to add in to define the animation.
<ul ref={(ul)=>{this.ul=ul}}>
<TransitionGroup>
<CSSTransition
timeout={1000}
classNames='boss-text'
unmountOnExit
appear={true}
key={index+item}
>
<li>1</li>
</CSSTransition>
<CSSTransition
timeout={1000}
classNames='boss-text'
unmountOnExit
appear={true}
key={index+item}
>
<li>2</li>
</CSSTransition>
</TransitionGroup>
</ul>
Copy the code
React animation has a lot of knowledge and can produce a lot of cool effects, which can be divided into a separate position. I use simple animation in my work, and the use of React-transition-group animation can fully meet my daily development needs
Most of the above content and explanations are from tech-fat blogs, combined with my own understanding of React.