home page
Statistics
sponsor
Leaving a message.
about
more
Friendly chain
wallpaper
live broadcast
Search
one
Joe - a personal Typecho theme
32064 Reading
two
Joe open source directory program system
11826 Reading
three
Typecho custom background editor function
8241 Reading
four
Joe theme is automatically updated
7507 Reading
five
Joe Theme Custom Matching Color Tutorial
4410 Reading
web front end
CSS
React
Vue 2.0
Vue 3.0
JavaScript
TypeScript
Typecho
Applet
MacCMS
other
life
Sign in
Search
https://78.al
Accumulated writing
seventy-six
Articles
Accumulated receipt
3,721
Comments
home page
column
web front end
CSS
React
Vue 2.0
Vue 3.0
JavaScript
TypeScript
Typecho
Applet
MacCMS
other
life
page
Statistics
sponsor
Leaving a message.
about
Friendly chain
wallpaper
live broadcast
Search to
six
Article and
React
Results for
2021-06-08
React Learning Note 6
React extension - setStatesetState Two writing methods for updating state 1. setState ({}, [callback]) export default class Test extends Component{
state = {count: 0}
add = () => {
const { count } = this.state
this.setState({ count: 8 })
Console. log (this. state. count)//0 Because setState is asynchronous, this will be executed first
//If you want to operate on the value in the state after the setState operation, you need to use the second callback function or async await implementation
this.setState({ count: 8 }, () => {
console.log(this.state.count) // 8
})
}
}2、setState(updater, [callback])export default class Test extends Component {
state = {count: 0}
add = () => {
//State and props can be obtained through functional expression
this.setState((state, props) => {
console.log(state, props)
return { count: state.count + 1 }
}, () => {
console.log(this.state.count) // 1
})
}
}React extension - lazy load route import {Component, lazy, Suspend} from "react"
//Lazy load routing module
const Home = lazy(() => import("./Home/index"))
const About = lazy(() => import("./About/index"))
export default class Test extends Component {
render() {
return (
<div>
{/* Suspend is used to display a loading */} when the network is bad
<Suspense fallback={<h1>Loading...</h1>}>
<Route path="/home" component={Home}>
<Route path="/about" component={About}>
</Suspense>
</div>
)
}
}React extension - State HookState Hook allows users to use stateimport React from 'react';
export default function Test2() {
//React. useState() is used to initialize a value and return an array
//The first value of the array is the initialized value
//The second value is a function used to modify the first value
const [count, setCount] = React.useState(0);
Const [name, setName]=React. useState ('Du Heng ');
//Click the callback of the event
const changeCount = () => setCount(count + 1);
Const changeName=()=>setName ('Handsome Du Heng ');
return (
<div>
<h2>The current value is: {count}</h2>
<button onClick={changeCount}>+ 1</button>
<hr />
<h2>Current name: {name}</h2>
<button onClick={changeName}>Rename</button>
</div>
);
}React extension - Effect HookEffect HookTo enable users to use the life cycle hook to import React from 'react';
export default function Test2() {
const [count, setCount] = React.useState(0);
//React.useEffect receives two parameters
//The first parameter is a function, which can be used as two life cycles
//ComponentDidMount or componentDidUpdate
//The second parameter is an array, which is used to listen to the value in the state
//If it is an empty array, the first parameter is used when componentDidMount (called only once)
//If the second parameter is not written or the array has a value, the first parameter is used when componentDidUpdate
React.useEffect(() => {
let timer = setInterval(() => {
setCount(count => count + 1);
}, 1000);
//When the return function goes out, the return function can be used as componentWillUnmount
return () => {
clearInterval(timer);
};
}, []);
return (
<div>
<h2>The current value is: {count}</h2>
</div>
);
}React extension - Ref HookRef Hook imports React from 'react' just like createRef in a class component;
export default function Test2() {
const inputRef = React.useRef();
const show = () => console.log(inputRef);
return (
<div>
<input type="text" ref={inputRef} />
<button onClick={show}>Click the prompt</button>
</div>
);
}React extension - when Fragment is used for multiple labels, the package uses import React, {Fragment} from 'react';
export default function Test2() {
return (
<Fragment>
<input type="text" />
<input type="text" />
</Fragment>
);
}The above writing method can be written as follows, using the empty tag import React, {Fragment} from 'react' directly;
export default function Test2() {
return (
<>
<input type="text" />
<input type="text" />
</>
);
}Contact extension - ContextContext is used for ancestor component to communicate with background component import Contact, {Component} from 'react';
// 1.
Create TestContext container
const TestContext = React.createContext();
export default class A extends Component {
State={name: 'Du Heng'};
render() {
return (
<div style={{ background: 'orange', padding: 10 }}>
I am Component A
{/* 2.
Pass all the states into the descendant components through the provider */}
<TestContext.
Provider value={this.state}>
<B />
</TestContext.
Provider>
</div>
);
}
}
class B extends Component {
render() {
return (
<div>
I'm Component B
<C />
</div>
);
}
}
//The first way
class C extends Component {
/* 3.
Declare to use context*/
static contextType = TestContext;
render() {
console.log(this.context); //
{name: "Du Heng"}
Return<div>I am a C component</div>;
}
}
//The second way
function C() {
return (
<div>
<TestContext.
Consumer>
{ value => console.log(value) }
</TestContext.
Consumer>
</div>
)
}React extension - the component optimization component has the following two problems: the setState is executed in the component. Even if the state data is not changed, the render will be triggered to update the parent component, and the render of the child component will also be triggered. Since the render is controlled by the shouldComponentUpdate valve, the operation import {Component} from 'react' needs to be performed in the shouldComponentUpdate hook;
export default class A extends Component {
state = { count: 0 };
/*Assigning an empty object does not change the value of state, but also triggers an update*/
add = () => this.setState({});
/*Control whether render is triggered by controlling the return value of shouldComponentUpdate*/
shouldComponentUpdate(nextProps, nextState) {
console.log(nextProps, nextState);
return !this.state.count === nextState.count;
}
render() {
Console. log ('render function triggered ');
return <button onClick={this.add}>{this.state.count}</button>;
}
}{callout color="# ab72da"} When there are few values in the state, it can be written like this, but when there is more data, it will not work. Therefore, another solution is to replace Component with PureComponent.
The logic in shouldComponentUpdate has been implemented by default in PureComponent. The above writing method can be changed to the following writing method {/call} import {PureComponent} from 'react';
export default class A extends PureComponent {
state = { count: 0 };
add = () => this.setState({});
render() {
Console. log ('render function triggered ');
return <button onClick={this.add}>{this.state.count}</button>;
}
}React extension - Render Propsimport {PureComponent} from 'react';
export default class A extends PureComponent {
render() {
return (
<div>
<h3>I am Component A</h3>
<B render={name => <C name={name} />}></B>
</div>
);
}
}
class B extends PureComponent {
State={name: 'Du Heng'};
render() {
return (
<div>
<h3>I'm Component B</h3>
{/* Slot like functions */}
{this.props.render(this.state.name)}
</div>
);
}
}
class C extends PureComponent {
render() {
console.log(this.props);
Return<div>I am a C component</div>;
}
}Error boundary The error boundary is used to control the error range of the parent component when the child component fails, without affecting other components.
The error boundary can only be used in the production environment. The development environment will flash import {PureComponent} from 'react';
export default class A extends PureComponent {
/*The parent component defines a state, which is used to determine whether there is an error*/
state = {hasError: ''};
/*This function will be triggered when there are errors in the life cycle of descendant components*/
static getDerivedStateFromError(error) {
return { hasError: error };
}
/*Here, you can catch the error and send it to the server. The server will notify the nail, etc*/
componentDidCatch() {
Console. log ('component error! ')
}
render() {
return (
<div>
<h3>I am Component A</h3>
{/* Dynamic rendering components */}
{this. state. hasError?<h2>Sub component error</h2>:<B/>}
</div>
);
}
}
class B extends PureComponent {
State={name: 'Du Heng'};
render() {
return (
<div>
<h3>I'm Component B</h3>
{this.state.name.map(() => (
<span>666</span>
))}
</div>
);
}
}
June 8, 2021
238 Reading
0 Comments
2 likes
2021-06-07
React Learning Note 5
What is ReduxRedux? Redux is a JS library specifically used for state management. It can be used in Vue, React, and Angular, but it is most often used with React: centralized management of the state shared by multiple components in React applications. Install redux and react reduxnpm i redux - S
Npm i react redux - SRedux uses the 1. src directory to create a redux folder,
The reducers folder is created in the redox folder to manage reducers. For example, a new reducer {callout color="# 51d2ad"} of count can initialize the state or operate the state {/callout}//The first prevState will default to undefined, so you can assign a value to it at this time and initialize a state value
//The action here is the object passed from the action in the second step
export default function countReducer(prevState = 0, action) {
switch (action.type) {
case 'add':
return prevState + action.data;
default:
return prevState;
}
}2. Create an actions folder in the redox folder to manage actions. For example, create a count action.//The action is used to distribute this object to the store, and then the reducer will process it
Export const createAddAction=data=>({type: 'add', data}); 3. Create a store file in the redux folder//createStore is used to create a store
//CombineReducers is used to integrate multiple reducers
import { createStore,
combineReducers } from 'redux';
import countReducer from './reducers/count';
const allReducer = combineReducers({
count: countReducer
});
export default createStore(allReducer);
4. Get the values in the store and distribute events to reducerimport {Component} from 'react' in the component;
//Used to connect to redux
import { connect } from 'react-redux';
//Used to distribute events
import { createAddAction } from '../../
redux/actions/count';
class Count extends Component {
add = () => {
this.props.add(1);
};
render() {
const { count } = this.props;
return (
<div>
<div>The current sum is: {count}</div>
<button onClick={this.add}>+</button>
</div>
);
}
}
//State=>({count: state. count}) State is the content in redux, which will be passed to the Count component
//{add: createAddAction} will pass an add event to the Count component. Calling the add method in the Count component will call createAddAction, and then React Redux will distribute the event to the reducer
export default connect(state => ({ count: state.count }), { add: createAddAction })(Count);
5. In the portal file, add a provider for the global public storeimport store from '/
redux/store';
import { Provider } from 'react-redux';
ReactDOM.render(
<Provider store={store}>
<App />
</Provider>,
document.querySelector('#root')
);
June 7, 2021
146 Reading
0 Comments
2 likes
2021-06-04
React Learning Note 4
React Router Dom first needs to install the routing dependency library. Note that the implementation of routing control with the name of react router domnpm i react router dom - S tag mode 1. First, wrap a BrowserRouter or HashRouter for the component in index.js. The difference between the two is whether there is a # link in the address bar,
This ensures that the routes in the whole project are the same router management import {BrowserRouter} from 'react router dom';
import App from './App';
ReactDOM.render(
<BrowserRouter>
<App />
</BrowserRouter>,
document.querySelector('#root')
);
2. In App.jsx, routing control is implemented through tags {callout color="# 4eda96"} In routing components (such as About and Home components), four props properties {/callout} import {Component} from 'react' will be received by default;
import { Link,
Route } from 'react-router-dom';
import About from './views/About/About';
import Home from './views/Home/Home';
export default class App extends Component {
render() {
return (
<div>
{/* Click to jump to the corresponding route */}
<NavLink to="/about" activeClassName="current">About</NavLink>
<NavLink to="/home" activeClassName="current">Home</NavLink>
{/* Use switch to improve matching efficiency */}
<Switch>
{/* Display corresponding components according to different routing addresses */}
<Route path="/about" component={About} />
<Route path="/home" component={Home} />
</Switch>
</div>
);
}
}Tips: There are three ways to solve the problem of resource loss in the secondary route refresh page/
Change the assets type to/assetspublic/index.html/
Change to% PUBLIC_URL% public/index.html and change BrowserRouter to HashRouter route redirection import {Component} from 'react';
import { Link,
Route, Redirect } from 'react-router-dom';
import About from './views/About/About';
import Home from './views/Home/Home';
export default class App extends Component {
render() {
return (
<div>
<NavLink to="/about" activeClassName="current">About</NavLink>
<NavLink to="/home" activeClassName="current">Home</NavLink>
<Switch>
<Route path="/about" component={About} />
<Route path="/home" component={Home} />
{/* When all routes do not match, redirection will be executed */}
<Redirect to="/about"/>
</Switch>
</div>
);
}
}Route parameter 1. Pass the params parameter to the route component News component import Detail from '/
Detail/Detail';
export default class News extends Component {
render() {
return (
<div>
<Link to="/home/news/detail/001">News 1</Link>
<Link to="/home/news/detail/002">News 2</Link>
<Link to="/home/news/detail/003">News 3</Link>
{/* Receive */} dynamically through colon
<Route path="/home/news/detail/:id" component={Detail} />
</div>
);
}
}Detail component export default class News extends Component{
render() {
{/* Here you will receive the passed parameter */}
console.log(this.props.match.params);
return <div>{this.props.match.params.id}</div>;
}
}2. Pass the search parameter to the routing component News component export default class News extends Component{
render() {
return (
<div>
<Link to="/home/news/detail/? Id=001">News 1</Link>
<Link to="/home/news/detail/? Id=002">News 2</Link>
<Link to="/home/news/detail/? Id=003">News 3</Link>
<Route path="/home/news/detail" component={Detail} />
</div>
);
}
}Detail component export default class News extends Component{
render() {
console.log(this.props.location.search);
return <div>Test</div>;
}
}3. Pass the state parameter to the routing component. When the browser record is cleared, the data of the News component export default class News extends Component will be lost{
render() {
return (
<div>
<Link to={{pathname: '/home/news/detail', state: {id:'001 '}}}>News 1</Link>
<Link to={{pathname: '/home/news/detail', state: {id: '002'}}}>News 2</Link>
<Link to={{pathname: '/home/news/detail', state: {id: '003'}}}>News 3</Link>
<Route path="/home/news/detail" component={Detail} />
</div>
);
}
}Detail component export default class News extends Component{
render() {
console.log(this.props.location.state);
return <div>Test</div>;
}
}Programmed route 1. Stacking jump (with history) export default class News extends Component{
linkTo = id => {
this.props.history.push({ pathname: '/home/news/detail', state: { id } });
};
render() {
return (
<button onClick={()=>this. linkTo ('001 ')}>News 1</button>
);
}
}2. Export default class News extends Component{
linkTo = id => {
this.props.history.replace('/home/news/detail',{ id });
};
render() {
return (
<button onClick={()=>this. linkTo ('001 ')}>News 1</button>
);
}
}General components add routing function {callout color="# 986de8"} By default, general components do not have routing function, so you need to use withRouter to implement routing function {/call} import {withRouter} from 'react router dom';
class Test extends Component {
go = () => {
console.log(this.props)
};
render() {
Return<button onClick={()=>this. go}>News 1</button>
}
}
export default withRouter(Test)
June 4, 2021
163 Reading
0 Comments
2 likes
2021-06-01
React Learning Note 3
Introduction to index.js generated by React scaffold import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import reportWebVitals from './reportWebVitals';
ReactDOM.render(
//When strict mode is enabled, the specification in the app component can be detected, such as using the string ref=""
<React.
StrictMode>
<App />
</React.
StrictMode>,
document.getElementById('root')
);
//Used to record page performance
reportWebVitals();
Sub components transfer values to parent components 1. Parent components export default class P extends Component{
addTodo = name => {
const { todos } = this.state;
};
render() {
return (
<div>
<Header addTodo={this.addTodo}/>
</div>
);
}
}2. Sub component export default class Header extends Component{
handleClick = () => {
this.props.addTodo(88888)
}
render() {
return (
<div onClick={this.handleClick}>
Test
</div>
);
}
}Value transfer between brother components (message subscription and publication) {message type="info" content="Message subscription and publication are usually implemented using the PubSubJS library"/} For example, there are two brother components A and B.
1. Component A needs to receive the data transferred from component B, so component A needs to subscribe to a message export default class A extends Component first{
state = {
items: [],
isFirst: true,
isLoading: false,
error: ''
};
componentDidMount() {
//Subscribe to a message called STATE
PubSub.subscribe('STATE', (msg, state) => {
console.log(msg, state)
if (msg === 'STATE') this.setState(state);
});
}
render() {
return (
<div></div>
);
}
}2. Component B publishes messages to component A export default class Search extends Component{
render() {
return (
<div>
<button onClick={this. searchUser}>Search</button>
</div>
);
}
/*Search Users*/
searchUser = () => {
PubSub.publish('STATE', { isFirst: false,
isLoading: true, error: '' });
};
}Realize array statistics by reducing. For example, count the number in the array whose done is true const arr=[
{
name: 'a',
done: true
},
{
name: 'b',
done: true
},
{
name: 'c',
done: false
}
]
const doneCount = arr.reduce((prev, current) => {
return prev + (current.done ?
1 : 0)
}, 0)
Console. log (doneCount)//In 2Ract, the proxy server can be configured in two cross domain ways {callout color="# 7f68f3"}. The principle of cross domain configuration: for example, the current project address is:
http://localhost:3000
, will open a micro
http://localhost:3000
The proxy server will send the request to the micro server after sending the request, and then the micro server will send the request to the server, and finally the micro server will forward the result to the current project address.
The microserver has no ajax engine, so there is no cross domain blocking problem {/call} 1. By modifying the package.json method, for example, the domain name and port of the server to be requested are
http://localhost:5000
In the package.json file, add the following options{
...,
"proxy": "
http://localhost:5000
",
"Proxy": "Domain name and port number of the server that needs proxy"
}For example, the address of the current startup project is
http://localhost:3000/
Then change the previous request address to the local address import {Component} from 'react';
import axios from 'axios';
export default class App extends Component {
getData = async () => {
try {
// const res = await axios.get('
http://localhost:5000/students
');
Before modification
const res = await axios.get('
http://localhost:3000/students
'); //
After modification
const res = await axios.get('/students'); //
Or change it to this
console.log(res);
} catch (e) {
console.log(e);
}
};
render() {
return <button onClick={this.getData}>click</button>;
}
}{callout color="# 4da9ef"} Tips: When the proxy server sends a request, it will give priority to the public folder. If there is a corresponding file, it will directly request the corresponding file. If there is no corresponding file, it will send a request to the server.
For example, when requesting localhost: 3000/index.html, instead of directly sending a proxy request to localhost: 5000/index.html, it directly requests the index.html file {/call} in the public folder;
module.exports = function (app) {
app.use(
/*The configuration will be triggered when the/api1 prefix is requested*/
proxy('/api1', {
/*Forward request to
http://localhost:5000
*/
target: '
http://localhost:5000
',
/*
*The control server receives the value of Host in the request header
*When it is true, the request host received by the server is
http://localhost:5000
*When it is false, the request host received by the server is
http://localhost:3000
*/
changeOrigin: true,
/*
*Rewrite request path
*Replace/api1 with null
*/
pathRewrite: {
'^/api1': ''
}
})
);
};
Send request import {Component} from 'react';
import axios from 'axios';
export default class App extends Component {
getData = async () => {
try {
//After the above proxy, the api1 here will be replaced with null. The actual requested address is
http://localhost:5000/students
const res = await axios.get('/api1/students');
console.log(res);
} catch (e) {
console.log(e);
}
};
render() {
return <button onClick={this.getData}>click</button>;
}
}React Scaffold Configuration Agent.md
June 1, 2021
227 Reading
0 Comments
2 likes
2021-05-31
React Learning Note 2
Class Login extends React
Component {
state = {
username: '',
password: ''
}
saveFormData = (type) => {
/*Return a function for event callback*/
return (event) => {
event.persist()
this.setState({
[type]: event.target.value
})
}
}
render() {
return (
<div>
<input placeholder="user name" onChange={this. saveFormData ('username ')}/>
<input placeholder="password" onChange={this. saveFormData ('password ')}/>
</div>
)
}
}
ReactDOM. render (<Login/>, document. querySelector ("# main")) implements class Login extends React
Component {
state = {
username: '',
password: ''
}
saveFormData = (type, value) => {
this.setState({ [type]: value })
}
render() {
return (
<div>
<input placeholder="user name" onChange={(event)=>{this. saveFormData ('username ',
event.target.value) }} />
<input placeholder="password" onChange={(event)=>{this. saveFormData ('password ',
event.target.value) }} />
</div>
)
}
}
ReactDOM. render (<Login/>, document. querySelector ("# main")) component life cycle (old) 1. life cycle hook class Count extends React
Component {
/*Priority implementation*/
constructor(props) {
console.log('Count---constructor');
super(props)
this.state = { count: 0 }
}
/*Hook to which the component will be attached*/
componentWillMount() {
console.log('Count---componentWillMount');
}
/*Hook for component rendering*/
render() {
console.log('Count---render');
return (
<div>
<h2>The current value is: {this. state. count}</h2>
<button onClick={this. addCount}>Click+1</button>
<button onClick={this. deleteComponent}>Uninstall components</button>
<button onClick={this. forceUpdateComponent}>Force Update</button>
</div>
)
}
/*Hook with rendered components*/
componentDidMount() {
console.log('Count---componentDidMount');
}
/*Hook where the component will be unloaded*/
componentWillUnmount() {
console.log('Count---componentWillUnmount');
}
/*
*
*Valves for control assembly update
*Each time you execute setState to update the state, you will ask this valve
*If true is returned, rendering is allowed; otherwise, the reverse is true
*If this hook is not written, the React bottom layer will supplement this function by default and return true
*
*/
shouldComponentUpdate() {
console.log('Count---shouldComponentUpdate');
return true
}
/*The hook that the component will update*/
componentWillUpdate() {
console.log('Count---componentWillUpdate');
}
/*Hook with component updated*/
componentDidUpdate() {
console.log('Count---componentDidUpdate');
}
addCount = () => {
let { count } = this.state
this.setState({ count: count + 1 })
}
deleteComponent = () => {
ReactDOM.unmountComponentAtNode(document.querySelector('#main'))
}
forceUpdateComponent = () => {
/*
*Force Update Component
*The state does not need to be modified without passing through the valve
*
*/
this.forceUpdate()
}
}2. When parent-child components are used, the child component has a componentWillReceiveProps hook/* A is the parent component*/
class A extends React.Component {
state = {
Name: 'Du Heng'
}
render() {
return (
<div>
<h2>I am Component A</h2>
<button onClick={this. changeName}>Click to transfer Props</button>
<B name={this.state.name} />
</div>
)
}
changeName = () => {
This. setState ({name: 'hahaha'})
}
}
/*B is a sub assembly*/
class B extends React.Component {
componentWillReceiveProps(props) {
Console. log ('Component B triggered componentWillReceiveProps', props);
}
render() {
Return<div>I am a B component and received {this. props. name}</div>
}
}3. Summary of the life cycle of the old version. In the initialization phase, the constructor is initialized first, then the componentWillMount component is mounted, then the render component is rendered, and then the componentDidMount component is rendered (commonly used)
In the update phase, first execute shouldComponentUpdate, whether the component is allowed to update the valve, then execute componentWillUpdate, the component will be updated, then execute render component, then execute componentDidUpdate, the component is updated, and then uninstall phase, execute componentWillUnmount, the component will be uninstalled (commonly used), and the component life cycle (new)
The summary and initialization phase of the new version of the life cycle first executes constructor initialization, and then executes getDerivedStateFromProps to obtain the derivation of state from props (map props to state)
Then execute the render component. Then execute the componentDidMount component. After rendering, in the update phase, execute getDerivedStateFromProps to obtain the derivation of state from props (map props to state)
Then execute shouldComponentUpdate whether the component can be updated. Then execute render component. Then execute getSnapshotBeforeUpdate to obtain the current snapshot (current information, and pass the information to the update completion hook) before the update is completed. Then execute componentDidUpdate component to complete the update (you can obtain the above snapshot information)
During the uninstallation phase, the componentWillUnmount component is about to be uninstalled. {callout color="# ff6800"} Compared with the old version of the lifecycle hook, three useless will hooks, componentWillMount componentWillUpdate componentWillReceiveProps, have been deleted and two new lifecycle hooks, getInspectedStateFromProps getSnapshotBeforeUpdate {/callout}, have been added
class Count extends React.
Component {
constructor(props) {
Console.log ('constructor executed ');
super(props)
this.state = { count: 0 }
}
/*If you want the value of state to be consistent with the value of props, you can use this hook*/
static getDerivedStateFromProps(props, state) {
console.log('getDerviedStateFromProps', props, state);
return null
}
render() {
Console. log ('render executed ');
return (
<div>
<h2>The current value is: {this. state. count}</h2>
<button onClick={this. addCount}>Click+1</button>
</div>
)
}
/*Component rendering completed*/
componentDidMount() {
Console. log ('componentDidMount executed ');
}
/*Whether components can be updated*/
shouldComponentUpdate() {
Console. log ('shouldComponentUpdate executed ');
return true
}
/*
*
*Take a snapshot before updating
*Call this hook before the dom update,
*And return a snapshot value
*This snapshot value can be obtained after the component is updated
*In this hook, you can get the current information
*
*/
/*Component update completed*/
componentDidUpdate(prevProps, prevState, snapshot) {
Console. log ('componentDidUpdate executed ',
prevProps, prevState, snapshot);
}
addCount = () => {
let { count } = this.statesafds
this.setState({ count: count + 1 })
}
}
May 31, 2021
187 Reading
1 Comments
0 likes
2021-05-20
React Learning Note 1
JSX syntax 1. Tags cannot be quoted, newlines are wrapped in parentheses, and there is only one root tag const H1=<h1>title</h1>
const Div = (
<div>
<h1>H1</h1>
<h2>H2</h2>
</div>
)2. Variable uses curly braces const id=1
Const name="Du Heng"
Const Div=<div data id={id}>{name}</div>3. Inline style and external style.//When using class, you need to write the className
const Div = <div className="box"></div>
//When inline styles are used, they need to be packaged as variable objects
const Div2 = <div style={{ color: '#ff6800',
fontSize: '30px' }}>Test</div>4、
Single label needs to be closed const div=(
<div>
<br />
<input />
</div>
)5. Cyclic array const arr=['vue ',' react ',' jquery ']
const Ul = (
<ul>
{ arr.map(item => <li key={item}>{item}</li>) }
</ul>
)Component 1. Functional component (simple component<three properties can be realized in hooks>) function Test(){
console.log(this) // undefined
Return<div>Test component</div>
}
ReactDOM. render (<Test/>, document. querySelector ("# main")) 2. Class Test extensions React
Component {
render() {
console.log(this); //
Component instance object created by Test class
Return<div>Test component</div>
}
}
/*
*
*First parse the Test tag and find the Test class
*In React, the Test class will be new, and then the render method on the instance object will be initialized
*
*/
ReactDOM. render (<Test/>, document. querySelector ("# main")) three attributes of component instance stateclass Weather extends React
Component {
render() {
console.log(this);
Return<h1>It's very hot today</h1>
}
}
ReactDOM. render (<Weather/>, document. querySelector ("# main")) prints this on the instance object of the class. You can see that a state attribute is hung on the instance object. The default value is nullclass Weather extends React
Component {
/*The constructor calls several times according to the number of instances on the page*/
constructor(props) {
super(props)
/*Attach a property to the current instance*/
this.state = { isHot: false }
/*Solve the problem that this points to undefined in changeWeather*/
this.changeWeather = this.changeWeather.bind(this)
}
/*Render is called 1+n times, the first time it enters the default execution, and then the state update triggers render*/
render() {
/*This points to the current instance, so you can access the state attribute through this*/
console.log(this);
/*The onClick bound function cannot be bracketed, or the function will be executed directly*/
Return<h1 onClick={this. changeWeather}>The weather today is very {this. state. isHot? 'Hot': 'Cool'}</h1>
}
/*
*
*ChangeWeather is mounted on the prototype object of Weather for use by the instance object of Weather,
*This in the function will point to the instance object of Weather only when the instance object of Weather calls this method
*Since the local strict mode will be enabled for the function in class, this in changeWeather will point to undefined
*However, the problem of this pointing needs to be solved, so it is necessary to change the pointing of this when initializing above
*
*/
changeWeather() {
console.log(this);
/*
*Status cannot be changed directly!
* this.state.isHot = !
this.state.isHot ×
*/
this.setState({
isHot: !this.state.isHot
})
}
}
The code above ReactDOM. render (<Weather/>, document. querySelector ("# main")) can be abbreviated as the following code class Weather extends React
Component {
//Directly assign values to the instanced object
state = { isHot: false }
//Directly assign values to the instanced object
changeWeather = () => {
console.log(this); //
This points to the current instantiated object
this.setState({ isHot: !this.state.isHot })
}
render() {
Return<h1 onClick={this. changeWeather}>The weather today is very {this. state. isHot? 'Hot': 'Cool'}</h1>
}
}
ReactDOM. render (<Weather/>, document. querySelector ("# main")
Component {
render() {
return <h1 data-age={this.props.age} data-sex={this.props.sex}>{this.props.name}</h1>
}
}
const person = {
age: 18,
Sex: "Male"
}
ReactDOM. render (<Person name="Du Heng" {... person}/>, document. querySelector ("# main")) 2. props attribute limits class Person extends React
Component {
/*Restrict the types passed in by props*/
static propTypes = {
name: PropTypes.string.isRequired,
age: PropTypes.number,
sex: PropTypes.string
}
/*Default value when props are not transmitted*/
static defaultProps = {
age: 18,
Sex: "Male"
}
render() {
return (
<ul>
<li>Name: {this. props. name}</li>
<li>Age: {this. props. age}</li>
<li>Gender: {this. props. sex}</li>
</ul>
)
}
}
ReactDOM. render (<Person name="Du Heng" age={23}/>, document. querySelector ("# main"))
Component {
constructor() {
super()
console.log(this.props); //
undefined
}
render() {
return <h1>{this.props.name}</h1>
}
}4. Functional component receives propsfunction Person (props){
console.log(props);
return <h1>{props.name}</h1>
}
ReactDOM. render (<Person name="Du Heng"/>, document. querySelector ("# main")) The three attributes of the component instance, refs1, and ref (obsolete) class Test extends React
Component {
/*Click to display the input content on the left*/
showInputValue = () => {
console.log(this);
alert(this.refs.input.value)
}
showBlurInputValue = e => {
e.persist();
console.log(e);
alert(e.target.value)
}
render() {
return (
<ul>
<li>
<input ref="input" type="text" />
<button onClick={this. showInputValue}>Click to display the left prompt</button>
</li>
<li>
<input onBlur={this. showBlurInputValue} type="text" placeholder="Pop up prompt for losing focus"/>
</li>
</ul>
)
}
}2. Refclass Test extends React
Component {
showInputValue = () => {
console.log(this.input);
alert(this.input.value)
}
render() {
return (
<div>
<input ref={node => (this.input = node)} type="text" />
<button onClick={this. showInputValue}>Click to display the left prompt</button>
</div>
)
}
}The callback function in the ref of the inline mode will trigger twice when updating the status. The first time it will get null, and the second time it will get the current node. If you want to avoid this problem, you can write the function as a class. The above method can be written as the following class Test extends React
Component {
/*Click to display the input content on the left*/
showInputValue = () => {
console.log(this.input);
alert(this.input.value)
}
/*Save input*/
saveInputRef = (node) => {
this.input = node
}
render() {
return (
<div>
<input ref={this.saveInputRef} type="text" />
<button onClick={this. showInputValue}>Click to display the left prompt</button>
</div>
)
}
}3. CreateRef form class Test extends React
Component {
myRef = React.createRef()
/*Click to display the input content on the left*/
showInputValue = () => {
console.log(this.myRef);
alert(this.myRef.current.value)
}
render() {
return (
<div>
<input ref={this.myRef} type="text" />
<button onClick={this. showInputValue}>Click to display the left prompt</button>
</div>
)
}
}
ReactDOM.render(<Test />, document.querySelector("#main"))
May 20, 2021
146 Reading
1 Comments
1 Like