Preparing for development Environment
Reactjs.org --> Get started --> Create a New React App 3. Create project NPX create-react-app my-appcdMy-app NPM start 4. Install dependency yarn install --> my-app ask price folder has yarn.lock fileCopy the code
File directory
1. Click a small icon in the browser window to modify the favicon.ico file. To use NPM, delete yarn.lock and node_modules files and run NPM installCopy the code
Use React to complete ToDoList
- Create SRC /index.js, introduce React and ReactDom, and mount them on root.
import React from 'react';
import ReactDom from 'react-dom';
ReactDom.render(<div>hello world</div>, document.getElementById('root'));
Copy the code
- Create a new component SRC/todolist.js
import React, { Component } from 'react';
class TodoList extends Component {
render() {
return( <div>TodoList</div> ); }} // Component exportexport default TodoList;
Copy the code
The placeholder component uses, Fragment
import React, { Component, Fragement } from 'react';
class TodoList extends Component {
render() {
return( <Fragement> <input > <ul> <li>learn react</li> <li>learn Component</li> </ul> </Fragement> ); }}Copy the code
React: Data-driven design ideas/event binding
1) React is a data-driven framework that uses this.setState({key: {} <input value = {this.state.inputValue} /> 3) {} <input value = {this.state.inputValue} /> 3) {} <input value = {this.state.inputValue} /> 3) {} <input value = {this.state.inputValue} /> 3) {} <input value = {this.state.inputValue} /> Pass. The bind (this) to change this points to the current component < input value = {this. State. InputValue} onChange = {this. HandleInputChange. Bind (this)} / >Copy the code
Implement TodoList add/remove function
<ul> {this.state.list.map((value, index) => {return <li key={index}>{value}</li>
})}
</ul>
Copy the code
2) Add list item handleKeyUp(e) {if(e.keycode === 13) {// Enter // Array list original values and input fields // expand operator copy new array const list = [...this.state.list, this.state.inputValue]; SetState ({list: list, inputValue:) {this.setState({list: list, inputValue:);' '}}})Copy the code
3) Delete the list item //bind(this, val) <ul> {this.state.list.map((value, index) => {return( <li key={index} onClick={this.handItemClick.bind(this, index)}> {value} </li> ) })} </ul> handItemClick(index) { // console.log(index); const list = [...this.state.list]; List. Splice (index, 1); this.setState({list}); }Copy the code
JSX syntax details
1)bind(this) separate out to write "input value = {this. State. InputValue} onChange = {this. HandleInputChange. Bind (this)} onKeyUp={this.handleKeyUp.bind(this)} />bindPull it out and write it in the function 2) Loop the list out and write it in the functiongetListItems() {
return this.state.list.map((value, index) => {
return(<li key={index} onClick={this.handitemclick.bind (this, index)}> {value} </li>)})forStatement, need to be written as htmlForCopy the code
Component related
Component splitting and component value passing
1. Component split: create a component SRC/todoitem.js and add todolist.js 2. <TodoItem content={value} /> <li> {this.props. Content} </li> 3. Communication between child and parent: Calls methods passed by the parent. Note that the parent modifies the scope as it passes the methodCopy the code
React Core Features
1. Declarative development (do not need to manipulate DOM, just need to define JS template and data, modify data can be) 2. Can coexist with other frameworks: there are mechanisms for decoupling from other frameworks, and the index. HTML page only has id='root'React is related to divs. Other divs can be implemented using other frameworks. They do not affect each other. Componentization 4. One-way data flow (the parent component can change from the data of the component, but the self-component cannot change from the parent component) 5. Functional programmingCopy the code
React lifecycle
- Props, State, and render functions
Note when the render function will be executed: When the component is first created, the render function will be executed again when the state data is changed. When the props data is changed, the render function will be executed againCopy the code
- Use ref in React:
Example: When you click BTN to obtain the distance between BTN and the top of the page window, you need to operate the DOM ref on the HTML tag, obtain the DOM node ref on the component, and obtain the JS instance of the componentCopy the code
<button onClick={this.handlebtnclick} ref={(button) => {this.btnelem = button}} >Copy the code
handleBtnClick() {
console.log(this.btnElem.clientTop); // 1
}
Copy the code
- SetState is asynchronous
handleBtnClick() {
console.log(this.divElem.innerHTML); // 1
const newCounter = this.state.counter + 1;
this.setState({
counter: newCounter
})
console.log(this.divElem.innerHTML); // 1
}
Copy the code
setState: Two functions take arguments, and the second function is executed after the first onehandleBtnClick() {
console.log(this.divElem.innerHTML); // 1
const newCounter = this.state.counter + 1;
this.setState(() => {
return{ counter: newCounter } }, () => { console.log(this.divElem.innerHTML); / / 2})}Copy the code
import React, { Component, Fragment } from 'react';
class Counter extends Component {
handleClick() { const newNumber = this.state.number + 1; This.setstate ({number: newNumber})} // Initialize constructor(props) {console.log()'constructor'); super(props); this.handleClick = this.handleClick.bind(this); This. state = {number: 1}} // Life cycle function: // Automatic execution before page mountcomponentWillMount() {
console.log('componentWillMount'); } // automatically executed when the page is renderedrender() {
console.log('render');
return(<div onClick={this.handleclick}> Hello world{this.number}</div>)} // the page is mounted automaticallycomponentDidMount() {
console.log('componentDidMount'); } // Automatic execution (data update) before update, returns a Boolean valueshouldComponentUpdate() {
console.log('shouldComponentUpdate');
// return true; / / returnfalse// The page will not be re-rendered in the render function to improve the performance of the pagereturn false; } // Automatically executed when updatingcomponentWillUpdate() {
console.log('componentWillUpdate'); } // The update is completecomponentDidUpdate() {
console.log('componentDidUpdate'); }}export default Counter;
Copy the code
Order of execution: componentWillMount –> render –> componentDidMount –> shouldComponentUpdate –> componentWillUpdate –> render –> componentDidUpdate
Before and after the page is mounted
Life cycle function usage example
- Bind global events after the page loads
import React, { Component } from 'react'; // class Counter extends Component {//handleClick// window. AddEventListener () {// Window. AddEventListener () {'click', () => {
// console.log('window click'); //}) //} //render() {
// return(<div onClick={this.handleClick.bind(this)}>hello ... </div>) // class extends Component {//handleClick() {
// console.log('window click'); / / / /}componentWillMount() {
// window.addEventListener('click', this.handleClick)
// }
// render() {
// return(<div>hello ... </div>) // } //componentWillUnmount() {
// window.removeEventListener('click', this.handleClick);
// }
// }
export default Counter;
Copy the code
- An ajax request
Install axios: NPM install axios --save restart project file to import axios package: import axios from'axios'; Ajax requests are typically written into the life cycle function componentDidMountCopy the code
Use of the Ant Design component library
NPM install antd --save index.js to import style import'antd/dist/antd.css'Import {List, Typography} from the component library'antd'; Use components in the component libraryCopy the code
Front-end routing in React
Different components are displayed to users based on different paths
- BrowserRouter, create a route;
- Route, routing item, configure the routing item address, display the corresponding components;
CNPM install react-router-dom --save index.js import {BrowserRouter, Route, Link} from'react-router-dom';
Copy the code
import React, { Component } from 'react';
import ReactDom from 'react-dom';
import { BrowserRouter, Route, Link } from 'react-router-dom';
import newList from './newList';
import newButton from './newButton';
import 'antd/dist/antd.css';
class Entry extends Component {
render() {
return (
<BrowserRouter>
<div>
<Route path='/list' component={newList} />
<Route path='/button' component={newButton} />
</div>
</BrowserRouter>
)
}
}
ReactDom.render(<Entry />, document.getElementById('root')); Open / / web page address: http://localhost:3000/list http://localhost:3000/buttonCopy the code
- Link between components. Example: Click button page button, jump list page.
Import the Link component, and then pass <Link to="/ page address"> Implement route redirectionCopy the code
import React, { Component } from 'react';
import { Button } from 'antd';
import { Link } from 'react-router-dom';
class newButton extends Component {
render() {
return (
<Link to="/list">
<Button type="danger"</Button> </Link>)}}export default newButton;
Copy the code
Link jump with parameters:
1. Pass parameters: <Link to="/list? a=123"> 或者 <Link to="/list/123"> 2. When configuring the Route item, add the following parameter to the path :id(pass the parameter into the variable ID for easy obtaining elsewhere) <Route path='/list/:id'Component = {newList} / > 3. To obtain parameters: render the print console. The log (this. Props. Location. Search); Or the console. The log (this. Props. Match. Params. Id);Copy the code