foreword
"Author's Homepage" : Sprite Youbai Bubbles
"Personal Website" : Sprite's personal website
"Recommendation Column" :
★ Java one-stop service ★
★ React from entry to proficiency ★
★ Cool front-end code sharing ★
★ From 0 to hero, the road to Vue becoming a god ★
★ uniapp-from construction to promotion ★
★ From 0 to hero, Vue becoming a god Road ★
★ One column is enough to solve the algorithm ★
★ Let’s talk about the architecture from 0 ★
★ The exquisite way of data circulation ★
★ The road to advanced backend ★
Article directory
1. Overview of React
React is a declarative, efficient and flexible JavaScript library for building user interfaces. Using React, you can combine short, independent pieces of code into complex UI interfaces. These pieces of code are called "components".
Try React Online Now
There are two ways to write the React framework, one is the script method (JavaScript tag introduction, practice use); the other is the react scaffolding method (commonly used).
script method
- Step 1: Introduce the react library and react-dom library in the page;
For step 1 , you can use the following code in the page to import the react library and react-dom library:
<script crossorigin src="https://cdn.jsdelivr.net/npm/[email protected]/umd/react.production.min.js"></script>
<script crossorigin src="https://cdn.jsdelivr.net/npm/[email protected]/umd/react-dom.production.min.js"></script>
Make sure to 17.0.2
replace with the version of React you want to use.
- Step 2 : Introduce Babel; JSX syntax is used in React, but the browser does not recognize JSX, so we need to introduce babel
For step 2, you can use the following code to import Babel and use JSX syntax:
<script src="https://cdn.jsdelivr.net/npm/@babel/[email protected]/babel.min.js"></script>
<script type="text/babel">
// 在此处编写React组件和代码
</script>
You can also choose to use Babel as a development dependency and use Babel for project builds. This allows better support for ES6+ syntax and more Babel plugins.
- Step 3 : Create a mount point.
For step 3, you can create a div element with a specific id in the HTML as a mount point for the React component. For example:
<div id="root"></div>
You can root
replace with any name you want.
After completing the above steps, you can start writing React components and rendering them to the mount point.
complete example
This is a complete sample code, including importing React library, importing Babel, creating a mount point, and a simple React component:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>React App</title>
<script crossorigin src="https://cdn.jsdelivr.net/npm/[email protected]/umd/react.production.min.js"></script>
<script crossorigin src="https://cdn.jsdelivr.net/npm/[email protected]/umd/react-dom.production.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/@babel/[email protected]/babel.min.js"></script>
</head>
<body>
<div id="root"></div>
<script type="text/babel">
// 创建一个名为Greeting的React组件
function Greeting(props) {
return <p>Hello, {
props.name}!</p>;
}
// 渲染Greeting组件到页面上的根元素
ReactDOM.render(<Greeting name="John" />, document.getElementById('root'));
</script>
</body>
</html>
In the above code, we import the production version of React library and ReactDOM library, and use Babel to parse the embedded JSX code. Then, we created a root
div with id in the page as the mount point of the React component.
Next, we define a React component called Greeting that takes props
a name
property named Greeting and returns an element containing the greeting p
.
Finally, we use ReactDOM.render
the method to render the Greeting component to the mount point on the page. In this example, the Greeting component will display "Hello, John!". You can modify the property values of the component as needed.
Scaffolding
Step 1 - Create a virtual DOM object
// 创建虚拟DOM对象
const vNode = React.createElement(
// 标签名
"div",
// 属性对象
{
id: "mydiv",
className: "cls",
},
// 标签内的内容
"hello react!"
);
Step 2 - Get the mount point
// 获取挂载点
const root = document.getElementById("root");
Step 3 - Render the page
// 渲染页面
ReactDOM.render(vNode, root);
full code
The full code is as follows:
<!DOCTYPE html>
<html>
<head>
<title>React 封装演示</title>
<script src="https://cdn.jsdelivr.net/npm/react/umd/react.development.js"></script>
<script src="https://cdn.jsdelivr.net/npm/react-dom/umd/react-dom.development.js"></script>
</head>
<body>
<!-- 挂载点:后续生成的内容插入这里 -->
<div id="root"></div>
<script type="text/javascript">
// 步骤1 - 创建虚拟DOM对象
const vNode = React.createElement(
// 标签名
"div",
// 属性对象
{
id: "mydiv",
className: "cls",
},
// 标签内的内容
"hello react!"
);
// 步骤2 - 获取挂载点
const root = document.getElementById("root");
// 步骤3 - 渲染页面
ReactDOM.render(vNode, root);
</script>
</body>
</html>
The above code is rendered in pure HTML, and you can see the rendered React component directly by opening it in the browser. In the code, the development versions of React and ReactDOM are first introduced. Then,
<div id="root"></div>
the mount point is set in the tab. Next, useReact.createElement()
the method to create a virtual DOM object, and set the tag name, attribute object and the content in the tag. Finally,document.getElementById("root")
get the mount point and useReactDOM.render()
the method to render the virtual DOM object to the mount point. In this way, a div tag with "id" and "className" attributes will be rendered on the page, and the content will be "hello
react!".
Component is a very important concept in React. It is responsible for dividing the page into independent and reusable parts, and can dynamically display content according to different inputs (props).
2. Components
Components are conceptually similar to JavaScript functions. It accepts any input parameter (props") and returns the React element used to describe the content displayed on the page. There are two ways to define components in React
Functional components
Functional components are a new syntax added after React 16.8. It is a simple and lightweight way to define components. We can use a function to declare a component, receive a parameter props, and return a React element to describe the display content of the page.
Here is a sample code for a simple functional component:
function Welcome(props) {
return <h1>Hello, {props.name}!</h1>;
}
// 使用该组件
const element = <Welcome name="John" />;
ReactDOM.render(
element,
document.getElementById('root')
);
In the above code, we define a function component named Welcome, which receives a props parameter, which can contain any attributes. Inside the component, we can use the properties in the props object to dynamically display the page content.
class-style components
Class-wise components are a more traditional and powerful way of defining components in React. We can define a component using a class that inherits React.Component and implements a render method to return React elements.
Here is a sample code for a simple class-style component:
class Welcome extends React.Component {
render() {
return <h1>Hello, {this.props.name}!</h1>;
}
}
// 使用该组件
const element = <Welcome name="John" />;
ReactDOM.render(
element,
document.getElementById('root')
);
In the above code, we define a class component named Welcome, which inherits React.Component, and then implements a render method to describe the display content of the component. In the render method, we can get the incoming properties through this.props and use them to dynamically display the content.
Whether it's a function or a class, a component is a function or class that takes props and returns a React element. They can flexibly display different content according to different props, so as to achieve componentization and reuse of pages.
3. Events
Event handling in React is very similar to event handling for DOM elements, with some syntactic differences. React uses camelCase to define events, and needs to pass in a function as the event handler instead of a string. Doing this ensures that event handlers are properly bound and executed in React components.
React handles the click event
Here is a sample code for handling click events with React:
class Button extends React.Component {
handleClick() {
console.log('Button clicked');
}
render() {
return <button onClick={this.handleClick}>Click me</button>;
}
}
ReactDOM.render(<Button />, document.getElementById('root'));
In the code above, we create a Button component and return a
<button>
element in the component's render method. On the element, we pass a function as the handler for the click event<button>
through the onClick attribute .this.handleClick
When the button is clicked, the event handler
handleClick
is called and a log message is output.It should be noted that in React, event handlers are automatically bound to component instances. So you can use in the event handler
this
to refer to the component instance.
There is also another way to use arrow functions to access component instances in event handlers.
arrow function
Here is a sample code for event handling using arrow functions:
class Button extends React.Component {
handleClick = () => {
console.log('Button clicked');
}
render() {
return <button onClick={this.handleClick}>Click me</button>;
}
}
ReactDOM.render(<Button />, document.getElementById('root'));
In the above code, we use the class attribute to define the event handling function, which can ensure that the internal of the arrow function is
this
consistent with the component instance.
To sum up, the event handling in React has some syntax differences from the event handling of DOM elements, but the overall idea is very similar. We can handle various user interaction events in React components by using small camel-case naming methods and passing in functions as event handlers.
summary
In this article, we started with an overview of React, a JavaScript library for building user interfaces. We also covered ways to install and run React using scripting and scaffolding.
Second , we discussed the concept of React components and two ways of defining components: the function way and the class way. The function method is a new syntax added after React 16.8, which is simpler and lighter. The class method is a traditional and powerful way to define components in React. It inherits React.Component and implements the render method to describe the display content of the component.
Finally , we learned how to handle events in React. React's event handling is similar to that of DOM elements, with some syntactic differences. React events are named in camel case, and a function needs to be passed in as the event handler.