Configure development environment
Scaffolding tool create-react-app
Reserve knowledge: terminal or command line, code editor
React official Chinese documentation
Get the address: click to get
create-react-app
It is a scaffolding tool for quickly building React projects based on Node.
npx create-react-app testdemo
cd testdemo
npm i
The npx command is a command introduced by npm v5.2.0. You can directly use the commands provided by this package without installing the scaffolding package.
Yarn is a package manager released by Facebook. It has the same functions as npm and is fast, reliable and secure.
React with TypeScript
npx create-react-app testdemo-ts --template typescript
cd testdemo
npm i
About TypeScript
-
TypeScript is a superset of JavaScript
-
Adding type checking to native JavaScript
-
Like ES6, it cannot currently be read directly by mainstream browsers.
Compile TypeScript
Compilers: ts-loader, awesome-typescript-loader and babel-loader
Compiler configuration file: tsconfig.json
{
"compilerOptions": {
"noImplicitAny": false, //不需要显示地声明变量的类型any
"target": "es5", //编译后的目标js版本
"lib": [
"dom",
"dom.iterable",
"esnext"
], //库文件,过这些库文件,告诉typescript编译器可以使用哪些功能
"allowJs": true, //允许混合编译js文件
"skipLibCheck": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true, //允许使用commonJs方式import默认文件
"strict": true,
"forceConsistentCasingInFileNames": true,
"noFallthroughCasesInSwitch": true,
"module": "esnext", //配置代码模块系统,Node.js的commonJs、ES6的esnext、requireJs的AMD
"moduleResolution": "node",// 决定编译器的工作方式
"resolveJsonModule": true,
"isolatedModules": true, //编译器会将每个文件作为单独的模块使用
"noEmit": true, //发生错误时候,编译器不会生成Js代码
"jsx": "react-jsx" //允许编译器支持编译react代码
},
"include": [
"src"
] //使用此选项列出我们需要编译的文件, “文件路径”选项需要文件的相对或绝对路径
}
Update to TypeScript
1、npm install --save typescript @types/node @types/react @types/react-dom @types/jest
2、所有js文件改为jsx文件
3、import react
React basics
About React
History of FE
HTML、CSS、JavaScript——Ajax——jQuery——Angular MVC——Vue、React MVVM
Why is React?
-
One-way data flow
-
You just need to describe what the UI (HTML) looks like, just like writing HTML
-
React is responsible for rendering the UI and updating the UI when the data changes
-
Virtual DOM
Snapshot technology similar to Docker or VMware’s Snapshot
-
Componentization
-
Keep interactions consistent
-
Maintain a unified visual style
-
Facilitates collaboration between programmers
-
Learn it once and use it at will (nirvana)
-
Develop web applications using React
-
Use React to develop mobile native applications (react-native)
-
VR (Virtual Reality) can be developed using React (react 360)
What is React?
React is a JavaScript library for building user interfaces (HTML pages)
Mainly used to write HTML pages or build web applications
From an MVC perspective, React is just the view layer (V), which is only responsible for rendering the view and does not provide complete M and C functions.
(In the classic MVC model, M refers to the business model, V refers to the user interface, and C refers to the controller. The purpose of using MVC is to separate the implementation codes of M and V, so that the same program can use different forms of expression. )
Origin: An internal project at Facebook
JSX
What is JSX?
What's this?HTML?JS?
const element = <h1>Hello,world!</h1>
This is ReactJS’s own language: JSX
-
JSX is not a standard ECMAScript syntax, just a syntax extension
-
For React projects, both js and jsx can be used
-
ts corresponds to tsx syntax
Extended reading: react-jsx, react-jsxdev
JSX is actually React.createElement
syntactic sugar. The two ways of writing in the figure below are completely equivalent:
Why is JSX?
-
React does not force the use of JSX, you can also use native JavaScript
-
React believes that the essence of a view is: the internal unity of rendering logic and UI view performance
-
React couples HTML with rendering logic to form JSX
Features of JSX
-
HTML code can be compatible with JSX
-
Expressions can be embedded in JSX
-
Specify child elements using JSX
Attention
-
React element attribute names use camelCase naming convention
-
Special attribute names: class->className, for->htmlFor, tabindex->tabIndex
-
If the element has no child nodes, it can be
/>
ended with
-
It is recommended to wrap JSX with parentheses to avoid the automatic semicolon insertion trap in JS.
Basic usage
Using (embedding) Js expressions in JXS
Data is stored in JS, syntax: {JavaScript expression} Note: The syntax is single curly brackets
const name = '张三'
// 1、使用JSX创建react元素
const title = <h1>Hello {name}</h1>
//2、渲染react元素
ReactDOM.render(title, document.getElementById('root'))
React DOM escapes all input content by default before rendering . It ensures that you never inject content into your application that you didn't explicitly write. All content is converted to strings before rendering. This can effectively prevent XSS (cross-site-scripting, cross-site scripting) attacks.
Further reading: How to prevent XSS attacks?
Conditional rendering of JSX
-
Scene: loading effect
-
Conditional rendering: JSX structure based on conditional rendering characteristics
-
This can be achieved using if/else or ternary operator or logical AND operator
const loadData = () => {
if (loading) {
return <div>loading...</div>
}
return <div>数据加载完成</div>
}
List rendering with JSX
-
You should use the map() method of array (mapping)
-
The key attribute should be added when rendering the list, and the value of the key attribute must be unique.
-
Principle: Add key attributes to whomever map() traverses
-
Note: Try to avoid using index numbers as keys
const songs = [
{ id: 1, name: '爱你' },
{ id: 2, name: '年少有为' },
{ id: 3, name: '南山南' },
]
// 1、使用JSX创建react元素
const list = (
<ul>
{songs.map(item => <li key={item.id}>{item.name}</li>)}
</ul>
)
JSX style processing
See for details: React’s inline styles and CSS
CSS of React
The way of import css file
-
Directly import the entire css file
import './index.css'
<div className="app">
It is simple to use, but may cause global pollution of styles and style conflicts.
-
JSS modular introduction components
import style from './index.css'
<div className={style.app}>
Additional configuration is required. The ts environment needs to configure *.d.ts
the type declaration file.
declare module "*.css" {
const css: {
[key: string]: string //约定:导出key所在的对象,原始的类名和内容都会和转化为这个对象
};
export default css;
}
CSS module/JSS
-
Each jsx or tsx file is treated as a separate original
-
All content contained in the original should also stand on its own
Further reading: CSS in Js
CSS & TypeScript
The advantage of Ts is to perform type checking for Js. So by converting CSS into Js objects through JSS, can you also add types to CSS?
Plugin:typescript-plugin-css-modules
npm i typescript-plugin-css-modules --save-dev
Add compilerOptions in the tsconfig.json file:
"plugins": [{
"name":"typescript-plugin-css-modules"
}]
Create a new .vscode folder - create a new file settings
{
"typescript.tsdk": "node_modules/typescript/lib",
"typescript.enablePromptUseWorkspaceTsdk": true
}
After configuration, you will find that there will be only prompts when writing style.
Media & fonts
src/assets/images
src/assets/fonts
src/assets/icons
State & Props
Difference
-
Props is the external interface of the component, and state is the internal interface of the component.
-
Props are used for data transfer between components, while state is used for data transfer within components.
State
State is a "private property" of the component
initialization
//构造函数constructor是唯一可以初始化state的地方
constructor(props){
super(props);
this.state = {
count: 0
}
}
Revise
//使用setState()修改数据,更新组件状态,调用render函数重新渲染
onClick = {() => {
this.setState({isOpen: !this.state.isOpen});
}}
Asynchronous updates are executed synchronously
After calling setState, the state will not change immediately, it is an asynchronous operation (React will merge multiple modifications into one). Therefore, do not rely on the current State to calculate the next State.
setState itself is not asynchronous, but the state processing mechanism gives the illusion of asynchronousness.
onClick = {() => {
this.setState((preState, preProps) => {
return {count: preState.count + 1}
},() => {
console.log("count" ,this.state.conut)
});
this.setState((preState, preProps) => {
return {count: preState.count + 1}
},() => {
console.log("count" ,this.state.conut)
});
}}
Props
Essentially, props are the parameters passed into the function, which are the data passed from the parent component to the child component.
parent component
<ul>
{robots.map(r => <Robot id={r.id} name={r.name} email={r.email}></Robot>)}
</ul>
Subassembly
//为Robot指定类型React.FC,FC(functional component)函数式组件的接口,接受泛型参数P(Props)
const Robot: React.FC<RobotProps> = (props) => {
const id = props.id;
const name = props.name;
const email = props.email;
return (<div className={styles.cardContainer}>
<img src={`https://robohash.org/${id}`} alt="robot" />
<h2>{name}</h2>
<p>{email}</p>
</div>
);
}
Immutable
Props are read-only and cannot be changed once created. Data can only be changed through destruction and reconstruction.
Advantages: By judging whether the memory is consistent, you can confirm whether the object has been modified, which greatly improves performance efficiency.
The way to write programs using Immutable is functional programming (component).
The article is reproduced from: https://www.cnblogs.com/gfhcg/p/17265829.html