Table of Contents
Basic syntax of React
1. React
2. The two implementation methods and differences of React components
Home Web Front-end JS Tutorial What are the basic syntaxes of React? Introduction to the basic syntax of react (with examples)

What are the basic syntaxes of React? Introduction to the basic syntax of react (with examples)

Sep 11, 2018 pm 02:32 PM

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 src="https://cdn.bootcss.com/react/15.4.2/react.min.js"></script>
<script src="https://cdn.bootcss.com/react/15.4.2/react-dom.min.js"></script>
<script src="https://cdn.bootcss.com/babel-standalone/6.22.1/babel.min.js"></script>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="react.js"></script>
    <script src="react-dom.js"></script>
    <script src="babel.min.js"></script>
    <script src="01.js" type="text/babel"></script>
</head>
<body>
<p id="content"></p>
</body>
</html>
Copy after login
 react.min.js - React 的核心库
react-dom.min.js - 提供与 DOM 相关的功能
babel.min.js - Babel 可以将 ES6 代码转为 ES5 代码,这样我们就能在目前不支持 ES6 浏览器上执
 行 React 代码。Babel 内嵌了对 JSX 的支持。通过将 Babel 和 babel-sublime 包(package)
一同使用可以让源码的语法渲染上升到一个全新的水平。
Copy after login

2.1 Method 1:

class MyTextView extends React.Component{
    render(){
        return <p>hello react</p>;
    }
}
//组件渲染到DOM中  
ReactDOM.render(<MyTextView></MyTextView>,document.body);
Copy after login
  • 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);
Copy after login
  • 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 contentText ={this.state.text}/>
            //注意属性onChange大写
            <input type="text" onChange={this.handleChange} ></input>
        </p>;
    }
});
ReactDOM.render(<MyViewGroup/>,document.getElementById("content"));
Copy after login
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 
            }); 
        } 
    }
Copy after login

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:[] //数组
        };
    }
Copy after login

2、props的初始化

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

render(){
    return <button className={`Button ${this.props.className}`} onClick={this.props.onClick}>{this.props.text}</button>;
}
Copy after login

本篇文章到这就结束了(想看更多就到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 of this Website
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

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

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What should I do if I encounter garbled code printing for front-end thermal paper receipts? What should I do if I encounter garbled code printing for front-end thermal paper receipts? Apr 04, 2025 pm 02:42 PM

Frequently Asked Questions and Solutions for Front-end Thermal Paper Ticket Printing In Front-end Development, Ticket Printing is a common requirement. However, many developers are implementing...

Who gets paid more Python or JavaScript? Who gets paid more Python or JavaScript? Apr 04, 2025 am 12:09 AM

There is no absolute salary for Python and JavaScript developers, depending on skills and industry needs. 1. Python may be paid more in data science and machine learning. 2. JavaScript has great demand in front-end and full-stack development, and its salary is also considerable. 3. Influencing factors include experience, geographical location, company size and specific skills.

Demystifying JavaScript: What It Does and Why It Matters Demystifying JavaScript: What It Does and Why It Matters Apr 09, 2025 am 12:07 AM

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

How to merge array elements with the same ID into one object using JavaScript? How to merge array elements with the same ID into one object using JavaScript? Apr 04, 2025 pm 05:09 PM

How to merge array elements with the same ID into one object in JavaScript? When processing data, we often encounter the need to have the same ID...

Is JavaScript hard to learn? Is JavaScript hard to learn? Apr 03, 2025 am 12:20 AM

Learning JavaScript is not difficult, but it is challenging. 1) Understand basic concepts such as variables, data types, functions, etc. 2) Master asynchronous programming and implement it through event loops. 3) Use DOM operations and Promise to handle asynchronous requests. 4) Avoid common mistakes and use debugging techniques. 5) Optimize performance and follow best practices.

How to achieve parallax scrolling and element animation effects, like Shiseido's official website?
or:
How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? How to achieve parallax scrolling and element animation effects, like Shiseido's official website? or: How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? Apr 04, 2025 pm 05:36 PM

Discussion on the realization of parallax scrolling and element animation effects in this article will explore how to achieve similar to Shiseido official website (https://www.shiseido.co.jp/sb/wonderland/)...

The difference in console.log output result: Why are the two calls different? The difference in console.log output result: Why are the two calls different? Apr 04, 2025 pm 05:12 PM

In-depth discussion of the root causes of the difference in console.log output. This article will analyze the differences in the output results of console.log function in a piece of code and explain the reasons behind it. �...

The Evolution of JavaScript: Current Trends and Future Prospects The Evolution of JavaScript: Current Trends and Future Prospects Apr 10, 2025 am 09:33 AM

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

See all articles