This is my third day of the August Challenge
1. Component introduction
- When you use React, you’re using components
- A component represents some functionality in a page
- Combine multiple components to achieve full page functionality
- Features: reusable, independent and combinable
2. Two ways to create a component
2.1 Using functions to create components
-
A component created using a js function (arrow function)
-
Convention 1: The function name must start with a uppercase letter. If it starts with a lowercase letter, an error is reported
-
Convention 2: Function components must have a return value that represents the structure of the component (return NULL can also render nothing, but no error is reported).
- Render function component: Use the function name as the component label name
- A component label can also be dual
function Hello(){
return(
<div>This is the function component</div>
)
}
ReactDOM.render(<Hello/>.document.getElementById('root'))
Copy the code
2.2 Using classes to create components
- Class components: Components created using ES6’s class
- Convention 1: Class names must begin with an uppercase letter
- Convention 2: Class components inherit from the React.componentparent class and can use methods or properties provided in the parent class
- Convention 3: Class components must provide the render() method
- Convention 4: The render() method must have a return value representing the structure of the component
class Hello extends React.Component{
render(){
return <div>Hello class Component!</div>
}
}
ReactDOM.render(<Hlello/>.document.getElementById('root'))
Copy the code
2.3 Extract as an independent JS file
Consider: How to organize the components in a project when there are many components? Option 1: Write all components in a js file Option 2: put all components in a separate JS file Component as an individual is usually placed in a separate JS file.
- Create a Hello. Js
- Import React in hello.js
- Create a component (function or class)
- Import the component in hello.js
- Import the Hello component in index.js
- Rendering component
hello.js
import React from 'react'
class Hello extends React.Component{
render(){
return(
<div>This is the first component</div>)}}/ / export
export default Hello;
Copy the code
index.js
// Modular syntax in ES6
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
// Import the Hello component
import Hello from './Hello'
ReactDOM.render(<Hello/>.document.getElementById('root'))
Copy the code