Getting started with React: How to create components in React
Create a component
Before creating a component, please pay attention to the following points:
The first letter of the name of the component must be capitalized
The JSX returned in the component can only be a root node, and all content must be framed by an element
1. Stateless functional component
None Stateful functional components can understand that achievements are generated by a function, making the code more readable, streamlined, convenient, and reducing redundancy. Stateless components have the following characteristics:
The component cannot be instantiated, and the overall rendering is improved
The component cannot access this object because it is not instantiated, so it cannot access this object
Components have no life cycle
Stateless components can only access input props and have no state
import React from 'react' import { connect } from 'dva'; function CreateComponent(props) { console.log(props); return ( <p> <span>{props.name}今年{props.age}岁</span> </p> ) } export default connect(state => ({ name:'小明', age:15 }))(CreateComponent);
2.React.Component class component
Each component class must implement a render method. Special attention should be paid here. This render method must return a JSX element, that is, wrap all content with an outermost element. If it returns a parallel Multiple JSX elements are illegal, as shown below:
import React from 'react' class CreateComponent extends React.Component { render() { return( <p> </p><h2 id="标题">标题</h2>
- 首先
- 其次
- 最后
The above example is to wrap the h2 element and ul with a p
1. Component event monitoring
import React from 'react' class CreateComponent extends React.Component { clickFunc = (e) => { console.log("监听:",e.target.innerHTML); } clickValue = (value) => { console.log(value); } render() { return ( <p> <a>监听事件</a> <br> <a>this对象</a> </p> ) } } export default CreateComponent;
The above is an example of event monitoring and parameter passing
2. Component state and setState
Usually in a component, state is used to put the status of the internal parameters of the component, and setState is used to change the parameters in the state, for example:
import React from 'react' class CreateComponent extends React.Component { state = { flag : true } clickValue = () => { this.setState({ flag: !this.state.flag }) } render() { return ( <p> <span>flag的值为:{this.state.flag ? '真' : '假'}</span> <br> <button>改变flag值</button> </p> ) } } export default CreateComponent;
3. The props of the component
props are the properties in the component. You cannot change your own props inside the component, such as , create a component, and then call this component in another component, as follows:
import React from 'react'; function NewComponent(props) { return ( <p> {props.content} </p> ); } export default NewComponent;
Create a component NewComponent, and then call it, as follows:
import React from 'react' import NewComponent from './newComponent.js' class CreateComponent extends React.Component { render() { return ( <p> <newcomponent></newcomponent> </p> ) } } export default CreateComponent;
It can be seen from here that props are components The attribute values brought in, props actually allow external components to configure themselves, and state is the component's control of its own state.
4. Component life cycle
Constructor component initialization:
constructor initializes some parameter properties, etc.
Before rendering the componentWillMount component:
componentWillMount This function slowly changed after react16.3.0 Deprecated, use componentDidMount instead
componentDidMountAfter component rendering:
componentDidMount is executed after component rendering, and data can be loaded
render component rendering:
render component rendering display page
import React from 'react' class CreateComponent extends React.Component { constructor () { super() console.log('construct:页面初始化') } componentWillMount () { console.log('componentWillMount:页面将要渲染') } componentDidMount () { console.log('componentDidMount:页面渲染结束') } render() { console.log('render:页面渲染'); return ( <p> 页面渲染 </p> ) } } export default CreateComponent;
Output result:
construct:页面初始化 componentWillMount:页面将要渲染 render:页面渲染 componentDidMount:页面渲染结束
componentWillUnmount component deletion
The componentWillUnmount function is a function that is executed before the component is to be deleted. The following code:
import React from 'react'; class NewComponent extends React.Component { componentWillUnmount() { console.log('componentWillUnmount:将要从页面中删除'); } render() { return ( <p> {this.props.content} </p> ); } } export default NewComponent;
Create a component NewComponent, and then introduce this component in the CreateComponent component, as follows:
import React from 'react' import NewComponent from "./newComponent.js"; class CreateComponent extends React.Component { constructor () { super() console.log('construct:页面初始化'); this.state = { content:'测试组件', isDelete:false } } componentWillMount () { console.log('componentWillMount:页面将要渲染') } componentDidMount () { console.log('componentDidMount:页面渲染结束') } deleteFunc = () => { this.setState({ isDelete:true }) } render() { console.log('render:页面渲染'); return ( <p> 页面渲染 <input> {!this.state.isDelete?( <newcomponent></newcomponent> ):(null)} </p> ) } } export default CreateComponent;
When the delete button is clicked At that time, the component NewComponent will be deleted, and the componentWillUnmount function will be executed before deletion
Output result:
construct:页面初始化 componentWillMount:页面将要渲染 render:页面渲染 componentDidMount:页面渲染结束 componentWillUnmount:将要从页面中删除
The above life cycles are the component life cycles we will commonly use, and the component life cycle There is also the life cycle of the update phase, but these are relatively rarely used. Here is a brief introduction:
shouldComponentUpdate(nextProps, nextState)
Use this method to control whether the component is updated. Rendering, if false is returned, it will not be re-rendered, as follows
import React from 'react' import NewComponent from "./newComponent.js"; class CreateComponent extends React.Component { constructor () { super() console.log('construct:页面初始化'); this.state = { content:'测试组件', isDelete:false } } componentWillMount () { console.log('componentWillMount:页面将要渲染') } componentDidMount () { console.log('componentDidMount:页面渲染结束') } shouldComponentUpdate(nextProps, nextState){ if(nextState.isDelete){ return false; } } deleteFunc = () => { this.setState({ isDelete:true }) } render() { console.log('render:页面渲染'); return ( <p> 页面渲染 <input> {!this.state.isDelete?( <newcomponent></newcomponent> ):(null)} </p> ) } } export default CreateComponent;
At this time, click the delete button and the page is not rendered. That is because the return value is set to false in shouldComponentUpdate. When the return value is false, The page cannot be re-rendered. The first parameter of this function represents the latest props, and the second parameter represents the latest state
componentWillReceiveProps(nextProps)
The component receives new props from the parent component Called before, the function parameter nextProps represents the received data
In the NewComponent component:
import React from 'react'; class NewComponent extends React.Component { componentWillUnmount() { console.log('componentWillUnmount:将要从页面中删除'); } componentWillReceiveProps(nextProps){ console.log(nextProps); } render() { return ( <p> {this.props.content} </p> ); } } export default NewComponent;
In the component CreateComponent:
import React from 'react' import NewComponent from "./newComponent.js"; class CreateComponent extends React.Component { constructor () { super() console.log('construct:页面初始化'); this.state = { content:'测试组件', isDelete:false } } componentWillMount () { console.log('componentWillMount:页面将要渲染') } componentDidMount () { console.log('componentDidMount:页面渲染结束') } changeFunc = () => { this.setState({ content:'文字修改' }) } render() { console.log('render:页面渲染'); return ( <p> 页面渲染 <input> {!this.state.isDelete?( <newcomponent></newcomponent> ):(null)} </p> ) } } export default CreateComponent;
However, componentWillReceiveProps will start in react16.3.0 Deprecated later
componentWillUpdate:
This method is called before the component is re-rendered and will be deprecated after react16.3.0
componentDidUpdate :
The component re-renders and changes the changes to the real DOM and then calls
Note: The three life cycles of componentWillUpdate, componentWillReceiveProps, and componentWillMount will be in react116 .Begin to be deprecated after 3.0
Related recommendations:
React component life cycle instance analysis
##React component Dragact 0.1.4 detailed explanation
The above is the detailed content of Getting started with React: How to create components in React. For more information, please follow other related articles on the PHP Chinese website!

C and JavaScript achieve interoperability through WebAssembly. 1) C code is compiled into WebAssembly module and introduced into JavaScript environment to enhance computing power. 2) In game development, C handles physics engines and graphics rendering, and JavaScript is responsible for game logic and user interface.

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

Dreamweaver Mac version
Visual web development tools

SublimeText3 English version
Recommended: Win version, supports code prompts!

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

WebStorm Mac version
Useful JavaScript development tools