React notes components-elements and components (1)

Introduction

What is a component?

Components are objects that can be combined with other objects.

const div = React.createElement('div',...)

This is a React element (the beginning of the div is lowercased),

const Div = () => React.createElement('div',...)

This is a React component (the beginning of Div is capitalized, and it is a function),

This way of writing is the agreed way of writing elements and components in React.

For now, a function that returns a React element is a component.

React two components

  1. Function component
function Welcome(props) {
	return <h1>Hello, {props.name}</h1>;
}

Instructions:<Welcome name="frank"/>

  1. Class component
class Welcome extends React.Component {
	render() {
    	return <h1>Hello, {props.name}</h1>
    }
}

Instructions:<Welcome name="frank"/>

<Welcome/> What will it ultimately be translated into?

<div/> Will be translated into React.createElement('div'), if it is a lowercase tag, such as div, it will be automatically translated into...create...(string), used to create a tag.

<Welcome/> Translated into React.createElement(Welcome), if the tag starts with capital, it will be translated into a...create...(function) to create a component.

How to verify that this statement is correct? Please use https://babeljs.io/repl/ for conversion, here are a few examples

Capital Div

Lowercase div

Uppercase Xxx

Lowercase xxx

The logic of React.createElement

  1. If a string div is passed in, then a virtual DOM will be created and returned.

  2. If a function is passed in, this function will be called, the return value of the function will be obtained, and a virtual DOM will be created to replace the original function position, for example:

const Welcome = () => {
	return <div class="content" title="I'm Content">I'm Content</div> 
}
<Welcome/>

Eventually <div class="content" title="I'm Content">I'm Content</div>it will replace <Welcome/>.

  1. If a class is passed in, an object of this class is constructed using the new keyword (and the constructor method is executed),
    a component object is obtained, and then the render method is called to obtain the return value of this method for rendering.
class Welcome extends React.Component {
	constructor() {
    	super()
        this.state = {n:0}
    }
	render() {
    	return <div>hi</div>
    }
}

Guess you like

Origin blog.csdn.net/cainiao1412/article/details/108375080