This is a series of React blogs organized by myself. It mainly refers to the content of the latest version of the official website of React that will be opened in March 2023. You are welcome to read the content of this series and hope to receive it.
After reading this article, you will gain:
- How to create and nest react components
- How to add markup and styles
- How to display data
- How to render conditionals and lists
- How to respond to events and update the screen
- How to share data between different components
1 How to create and nest react components
React applications are made up of components, which are parts of the user interface (UI) that have their own logic and appearance. The range of components is very large, it can be a complete page or a small button component. After react16, it is recommended that you use functional components combined with hooks to complete react application development*.
Note: If you don't know what functional components and hooks are, ignore these two concepts first, and we will introduce them later.
As a simple example, the following lines of code define the simplest react component:
function MyButton() {
return (
<button>我是一个按钮</button>
)
}
MyButton
Then, you can use this component in other react components :
export default function MyApp() {
return (
<div>
<h1>欢迎学习React</h1>
<MyButton />
</div>
);
}
As shown in the chestnut above, MyApp
it is a parent component that calls MyButton
the component, so MyButton
it is also called a child component. Run the code above and you'll see:
Special note: It should be noted that the component names defined in React start with uppercase and follow the big camel case naming rules.
2 Write markup using JSX
The markup syntax that appeared in the previous sample code is called JSX (Javascript XML, an extension language of javascript), and its main feature is to write markup language in js code . Writing React components using JSX is optional, but most React projects will use JSX because it's really sweet and convenient (if you've used the optional API).
JSX is stricter than HTML. For example, you need to use <br />
instead <br>
, your component cannot return multiple JSX tags - if the component consists of multiple side-by-side tags, it needs to be used <div> ... </div>
or <> ... </>
wrapped in the outermost layer, as shown in the following code:
function AboutPage() {
return (
<>
<h1>About</h1>
<p>Hello there.<br />How do you do?</p>
</>
);
}
3 Add styles to your components
In React components, you can use to className
add a name to the element - just like setting the element in vue
the , but with a different name:template
class
function AboutPage() {
return (
<>
<h1 className="title">About</h1>
<p>Hello there.<br />How do you do?</p>
</>
);
}
If you want to add styles to this component, you can create a AboutPage.css
file and write the styles in it:
.title {
font-size: 24px;
color: green;
}
Then, AboutPage.js
reference the css style in:
import "./AboutPage.css";
function AboutPage() {
...
}
In addition to this way of writing, you can also define a AboutPage.module.css
file with the same content AboutPage.css
as:
.title {
font-size: 24px;
color: green;
}
Then AboutPage.js
use it like this:
import styles from "./AboutPage.module.css";
function AboutPage() {
return (
<>
<h1 className={
styles.title}>About</h1>
<p>Hello there.<br />How do you do?</p>
</>
);
}
The advantage of this is: due to the use module css
, the style pollution problem caused by the duplicate css name is avoided, and I prefer to use this way of writing.
4 Display data
JSX allows you to write markup language in Javascript code, and also supports the use of curly braces {}
to escape data into Javascript, so you can embed some variables in JSX:
return (
<h1>
{
user.name}
</h1>
);
Using curly braces, you can also set attributes in the markup language as variables, for example: className="avatar"
put the "avatar" string as a CSS class name, but src={user.imageUrl}
put user.imageUrl
the variable value as img
the tag's src attribute:
return (
<img
className="avatar"
src={
user.imageUrl}
/>
);
Going a step further, you can also treat object
types of data as variables:
return (
<>
<h1>{
user.name}</h1>
<img
className="avatar"
src={
user.imageUrl}
alt={
'Photo of ' + user.name}
style={
{
width: user.imageSize,
height: user.imageSize
}}
/>
</>
);
}
Note: In this example,
style={ {}}
it is not a special syntax, the innermost one{}
is just the curly braces around an object.
5 Conditional rendering
There is no special syntax for writing conditional judgments in React (like , vue
can be used in v-if
) , if you need to write conditional rendering statements, you only need to use or other branch statements v-else
like in Javascript . if-else
As in the following example:
let content;
if (isLoggedIn) {
content = <AdminPanel />;
} else {
content = <LoginForm />;
}
return (
<div>
{
content}
</div>
);
Of course, you can also use ternary expressions to make the code look more elegant:
<div>
{
isLoggedIn ? (
<AdminPanel />
) : (
<LoginForm />
)}
</div>
If you don't need to use the else branch, you can also write it like this:
<div>
{
isLoggedIn && <AdminPanel />}
{
isLogined ? <AdminPanel /> : null}
</div>
The writing of these conditional branches is also valid for attributes in JSX.
6 Render List
Suppose you have a list of product data like this:
const products = [
{
title: 'Cabbage', id: 1 },
{
title: 'Garlic', id: 2 },
{
title: 'Apple', id: 3 },
];
In React components, you can map()
convert this array into <li>
an array using a function:
const listItems = products.map(product =>
<li key={
product.id}>
{
product.title}
</li>
);
return (
<ul>{
listItems}</ul>
);
Note: Components
map
generated using traversal have a property, **For each item in the list, a string or number should be passed to the key property to uniquely identify the item among its siblings. **Usually, the value of key should come from your data, such as database ID. If your component subsequently inserts, deletes, or reorders items, React can use the key to distinguish who is who, thereby optimizing rendering performance.<li>
key
7 Responding to events
You can respond to events by declaring event handlers in your components:
function MyButton() {
function handleClick() {
alert('You clicked me!');
}
return (
<button onClick={
handleClick}>
Click me
</button>
);
}
Note: There are no parentheses
onClick={handleClick}
afterhandleClick
, you don't need to add parentheses here .
8 Update screen
Typically, you want your component to remember some data from the component and display it. For example, you want to count the number of times a button is clicked. To achieve this, you need to add a state
(state) to the component, and you need to use the first hook
function - useState
:
import {
useState } from 'react';
count
Then you can declare a variable and the corresponding update function as follows setCount
, these are useState
provided, just write as follows:
function MyButton() {
const [count, setCount] = useState(0);
Then, you get two things: the current state ( count
) and the update function of the state setCount
. You can set their names at will, but they are generally [something, setSomething]
named according to the style of .
count
The default value that will be displayed when the MyButon component is rendered for the first time 0
. If you want to update count
the value, just call setCount()
the method to update its value:
function MyButton() {
const [count, setCount] = useState(0);
function handleClick() {
setCount(count + 1);
}
return (
<button onClick={
handleClick}>
Clicked {
count} times
</button>
);
The above code has implemented a fully-fledged state
React component. When you click the button, count
the value of will be +1. If you render the same component multiple times, each component will have its own independent state, as in the following code:
import {
useState } from 'react';
export default function MyApp() {
return (
<div>
<h1>Counters that update separately</h1>
<MyButton />
<MyButton />
</div>
);
}
function MyButton() {
const [count, setCount] = useState(0);
function handleClick() {
setCount(count + 1);
}
return (
<button onClick={
handleClick}>
Clicked {
count} times
</button>
);
}
operation result:
9 Using Hooks
By convention, use
the function starting with is called Hooks
, useState
which is a built-in hook function of React. You will learn more hook functions in the follow-up study, and you can also check it in the API reference . You can also write your own hooks by combining existing hooks.
Compared with other functions, hooks
it is more restrictive: you can only call hooks on top of components (or other hooks), if you want to use them in conditions or loops useState
, you need to extract a new component and put it useState
in the correct position, Otherwise React will give warnings or even errors.
10 Sharing data among components
In the previous chestnut, MyButton
the components exclusively share the data count
, so clicking one of MyButton
the components will not affect the value of the other:
so the question is, if you want two components to share data, what should you do?
If you want two sibling MyButton
components to share data, you need to move the state up into their common parent component MyApp
:
now, when you click either button, MyApp
the component count
will be updated, and the value in both components count
will be updated at the same time. So, how to write the code? Look at the code below:
export default function MyApp() {
const [count, setCount] = useState(0);
function handleClick() {
setCount(count + 1);
}
return (
<div>
<h1>Counters that update separately</h1>
<MyButton count={
count} onClick={
handleClick} />
<MyButton count={
count} onClick={
handleClick} />
</div>
);
}
Pay attention to the content of the change: 1. Move the sum count
from setCount
the MyButton
component to the middle MyApp
; 2. MyButton
Add count
the sum to the component onClick
(the data passed or the response function is called props
), count
which is the value passed from the parent component to the child component count
; onClick
yes Event handler function, once MyButton
the button in is clicked, the function will be executed once in the parent component handleClick
.
And MyButton
the component will look like this:
function MyButton({
count, onClick }) {
return (
<button onClick={
onClick}>
Clicked {
count} times
</button>
);
}
The result of running the above code is as follows:
The end of this article, ( ▽ ).