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!

JavaScript core data types are consistent in browsers and Node.js, but are handled differently from the extra types. 1) The global object is window in the browser and global in Node.js. 2) Node.js' unique Buffer object, used to process binary data. 3) There are also differences in performance and time processing, and the code needs to be adjusted according to the environment.

JavaScriptusestwotypesofcomments:single-line(//)andmulti-line(//).1)Use//forquicknotesorsingle-lineexplanations.2)Use//forlongerexplanationsorcommentingoutblocksofcode.Commentsshouldexplainthe'why',notthe'what',andbeplacedabovetherelevantcodeforclari

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.


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.

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Zend Studio 13.0.1
Powerful PHP integrated development environment

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),
