React is a popular JavaScript library for building user interfaces, particularly single-page applications where you need a fast and interactive user experience.
Here are the main components and concepts in React:
Components
Functional Components
These are JavaScript functions that return React elements. They are typically used for presentational purposes and are simpler to write.
function Greeting(props) {
return <h1>Hello, {props.name}</h1>;
}
Class Components
These are ES6 classes that extend from React.Component
and must include a render
method. They can hold and manage state and lifecycle methods.
class Greeting extends React.Component {
render() {
return <h1>Hello, {this.props.name}</h1>;
}
}
Note:
HTML elements should be written in lowercase, while custom React components should start with an uppercase letter. For example, “Greeting” should not be written as “greeting”.
If we need to pass parameters to a component, we can use the this.props object.
When adding attributes, the class attribute should be written as className, and the for attribute should be written as htmlFor, because class and for are reserved words in JavaScript.
Note that a component class can only contain a single top-level tag, otherwise an error will occur.
Exercise
Use class component to transfer information and render it in the root node.
App.js
import Button from "./Button"
import React from "react";
class Greeting extends React.Component {
render() {
return <h1>Hello, {this.props.name}</h1>;
}
}
export default function App() {
return <Greeting name="James"></Greeting>;
}
Combining Components
We can synthesize a component by creating multiple components, separating the different functional points of the component.
App.js
import Button from "./Button"
import React from "react";
function Name(props) {
return <h1>website:{props.name}</h1>;
}
function Url(props) {
return <h1>URL:{props.url}</h1>;
}
export default function App() {
return (
<div>
<Name name="weiy" />
<Url url="https://www.weiy.cc" />
</div>
);
}