search
HomeWeb Front-endJS TutorialWhat are the basic syntaxes of React? Introduction to the basic syntax of react (with examples)

This article mainly introduces the basic syntax of react, as well as a detailed explanation of the initialization methods of state and props. Next, let us read this article together

Basic syntax of React

1. What is React
2.React component
3 State and Props
4 React component life cycle

1. React

React is a JAVASCRIPT library used to build user interfaces.
React is mainly used to build UI. Many people think that React is the V (view) in MVC.
React originated as an internal project at Facebook, used to build the Instagram website, and was open sourced in May 2013.
React has high performance and very simple code logic. More and more people have begun to pay attention to and use it.

React uses JSX instead of regular JavaScript. JSX is a JavaScript syntax extension that looks a lot like XML.
Note

  • HTML tags in JSX use lowercase letters, and React components start with uppercase letters

  • Attributes are named using small camel case, the first one The first letter of the word is lowercase and the other uppercase letters start with

  • . Pay attention to the attributes of HTML tags such as onclick and onchange. In JSX, onClick must be written in small camel case for naming to be effective.

  • In order to support JSX, you need to set javascript in WebStrom to JSX Harmony

React features:
1. Declarative design −React adopts a declarative paradigm, which can easily describe applications.
2. Efficient −React minimizes interaction with the DOM by simulating the DOM.
3. Flexible −React works well with known libraries or frameworks.
4.JSX − JSX is an extension of JavaScript syntax. JSX is not required for React development, but it is recommended.
5. Components - Building components through React makes it easier to reuse code and can be well applied in the development of large projects.
6. One-way response data flow − React implements one-way response data flow, thereby reducing duplicate code, which is why it is simpler than traditional data binding.

2. The two implementation methods and differences of React components

Because React is a JAVASCRIPT library used to build user interfaces, so first reference three js files, or you can Download it and reference it locally.

<script></script>
<script></script>
<script></script>


    <meta>
    <title>Title</title>
    <script></script>
    <script></script>
    <script></script>
    <script></script>


<p></p>

 react.min.js - React 的核心库
react-dom.min.js - 提供与 DOM 相关的功能
babel.min.js - Babel 可以将 ES6 代码转为 ES5 代码,这样我们就能在目前不支持 ES6 浏览器上执
 行 React 代码。Babel 内嵌了对 JSX 的支持。通过将 Babel 和 babel-sublime 包(package)
一同使用可以让源码的语法渲染上升到一个全新的水平。

2.1 Method 1:

class MyTextView extends React.Component{
    render(){
        return <p>hello react</p>;
    }
}
//组件渲染到DOM中  
ReactDOM.render(<mytextview></mytextview>,document.body);
  • must inherit React.Component

  • render( ) The rendering function is a required

  • >A required method to create a virtual DOM. This method has special rules:
    1. It can only pass this.props and this. state access data
    2. Can return null, false or any React component
    3. Cannot change the state of the component
    4. Cannot modify the output of the DOM

##2.2 Method 2:

var MyTexTiew2  = React.createClass(
    {
        render:function () {
            return  <p>hi react</p>;
        }
    }
    );
ReactDOM.render(<mytextiew2></mytextiew2>,document.body);
  • Use the createClass method, pass in the object, structure assignment render and other methods and properties

  • The component will be executed only when this method is used Only the declaration cycle function of the component can access the component's state and props properties.

State and Props

State is mainly used to update the interface. The component's State property is initialized in the life cycle function getInitialState. When calling this.setState of the component When the state is changed, the component will be re-rendered and refreshed.

Props are mainly used to transfer data between components, that is, the pname attribute of the label can be obtained through this.props.pname in MyText

var MyTextView = React.createClass(
    {
     render:function(){
         return <p>content:{this.props.contentText}</p>;
     }
    }
);
var MyViewGroup = React.createClass({
    getInitialState:function () {
    //生命周期函数,返回一个对象
      return {text:""};
    },
    handleChange:function (e) {
    //改变组件的state属性
        this.setState({text:e.target.value});
    },
    render:function () {

        return <p>
            <mytextview></mytextview>
            //注意属性onChange大写
            <input>
        </p>;
    }
});
ReactDOM.render(<myviewgroup></myviewgroup>,document.getElementById("content"));
React component life cycle

Instantiation

First instantiation

getDefaultProps
getInitialState
componentWillMount
render
componentDidMount

Update after instantiation is completed

getInitialState
componentWillMount
render
componentDidMount

Existence period

State changes when the component already exists
componentWillReceiveProps
shouldComponentUpdate
componentWillUpdate
render
componentDidUpdate

Destruction & Cleanup Period

The componentWillUnmount

life cycle provides a total of 10 different APIs.

1.getDefaultProps

Acts on the component class and is only called once. The returned object is used to set the default props. The reference value will be shared in the instance.

2.getInitialState

Acts on the instance of the component. It is called once when the instance is created to initialize the state of each instance. This.props can be accessed at this time.

3.componentWillMount

Called before completing the first rendering, the state of the component can still be modified at this time. (If you want to see more, go to the PHP Chinese website
React Reference Manual column to learn)

4.render
必选的方法,创建虚拟DOM,该方法具有特殊的规则:
   只能通过this.props和this.state访问数据
   可以返回null、false或任何React组件
   只能出现一个顶级组件(不能返回数组)
   不能改变组件的状态
   不能修改DOM的输出

5.componentDidMount
真实的DOM被渲染出来后调用,在该方法中可通过this.getDOMNode()访问到真实的DOM元素。此时已可以使用其他类库来操作这个DOM。
在服务端中,该方法不会被调用。

6.componentWillReceiveProps
组件接收到新的props时调用,并将其作为参数nextProps使用,此时可以更改组件props及state。

componentWillReceiveProps: function(nextProps) { 
        if (nextProps.bool) { 
            this.setState({ 
                bool: true 
            }); 
        } 
    }

7.shouldComponentUpdate
组件是否应当渲染新的props或state,返回false表示跳过后续的生命周期方法,通常不需要使用以避免出现bug。在出现应用的瓶颈时,可通过该方法进行适当的优化。
在首次渲染期间或者调用了forceUpdate方法后,该方法不会被调用

8.componentWillUpdate
接收到新的props或者state后,进行渲染之前调用,此时不允许更新props或state。

9.componentDidUpdate
完成渲染新的props或者state后调用,此时可以访问到新的DOM元素。

10.componentWillUnmount
组件被移除之前被调用,可以用于做一些清理工作,在componentDidMount方法中添加的所有任务都需要在该方法中撤销,比如创建的定时器或添加的事件监听器。

通过集成extends React.Component  给组件初始化不会执行getDefaultProps、getInitialState
只有通过以下方式给组件初始化state和props

1、state的初始化,通过构造函数

  //在构造函数中对状态赋初始值
    constructor(props){
        super(props);//第一步,这是必须的
        //不能调用state
        this.state = {//第二步,赋初始值
            time:0,
            on:false,
            log:[] //数组
        };
    }

2、props的初始化

class Button extends React.Component{
//静态属性,给属性赋默认值
static defaultProps = {
    onClick : null,
    className : '',
    text : '默认'
};

render(){
    return <button>{this.props.text}</button>;
}

本篇文章到这就结束了(想看更多就到PHP中文网React使用手册栏目中学习),有问题的可以在下方留言提问。

The above is the detailed content of What are the basic syntaxes of React? Introduction to the basic syntax of react (with examples). For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
JavaScript in Action: Real-World Examples and ProjectsJavaScript in Action: Real-World Examples and ProjectsApr 19, 2025 am 12:13 AM

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.

JavaScript and the Web: Core Functionality and Use CasesJavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AM

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 the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

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 vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

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.

Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

From C/C   to JavaScript: How It All WorksFrom C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

MantisBT

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.

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools