search
HomeWeb Front-endJS TutorialDetailed explanation of the usage of props and state attributes in React (code example)

This article brings you a detailed explanation of the usage of props and state attributes in React (code examples). It has certain reference value. Friends in need can refer to it. I hope it will help You helped.

This article mainly introduces the specific usage of React props and state attributes, which has certain reference value. Friends in need can refer to it. If there are any deficiencies, criticisms and corrections are welcome.

props

I don’t know if you still remember the attributes in the xml tag, like this:

<class>
 <student>John Kindem</student>
 <student>Alick Ice</student>
</class>

What such an xml file expresses is that there are two students in Class 1. The student with student number 1 is named John Kindem, and the student with student number 2 is named Alick Ice. The id is the attribute. You can think of it as A constant that is read-only.
html inherits from xml, and JSX is an extension of html and js in some sense. The concept of attributes has naturally been inherited.
In React, we use the concept of props to pass read-only values ​​to the React component, like this:

// 假设我们已经自定义了一个叫Hello的组件
ReactDom.render(
  <hello></hello>,
  document.getElementById('root')
);

When calling the React component, we can pass some constants to the component as above , so that the component can be called internally. The calling method is as follows:

class Hello extends React.Component {
  constructor(props) {
    super(props);
  }
 
  render() {
    return (
      <p>
        </p><h1 id="Hello-this-props-firstName-this-props-lastName">Hello, {this.props.firstName + ' ' + this.props.lastName}</h1>
      
    );//欢迎加入前端全栈开发交流圈一起学习交流:864305860
  }//面向1-3年前端人员
}//帮助突破技术瓶颈,提升思维能力
 
ReactDom.render(
  <hello></hello>,
  document.getElementById('root')
);

To obtain the passed props inside the component, you only need to use this.props object, but before using it, remember to overwrite the constructor of the component and accept it The value of props is used to call the parent class constructor.
Of course, props can also set default values, as follows:

class Hello extends React.Component {
  constructor(props) {
    super(props);
  }
 
  static defaultProps = {
    firstName: 'John',
    lastName: 'Kindem'
  };
 
  render() {
    return (
      <div>
        <h1 id="Hello-this-props-firstName-this-props-lastName">Hello, {this.props.firstName + ' ' + this.props.lastName}</h1>
      </div>
    );//欢迎加入前端全栈开发交流圈一起吹水聊天学习交流:864305860
  }//面向1-3年前端人员
}//帮助突破技术瓶颈,提升思维能力
 
ReactDom.render(
  <hello></hello>,
  document.getElementById('root')
);

Just declare a static props default value in the ES6 class, and the running effect is the same as above.
Props are not complicated and can be learned with a little practice.

state, component life cycle

You may recall, what if I want to add dynamic effects to a React component? This problem needs to be solved using the state of the React component. State means state. In React, all changing control variables should be put into state. Whenever the content in the state changes, the corresponding component of the page will be Re-rendering. In addition, state is completely internal to the component. State cannot be transferred from the outside to the inside, nor can the value of state be directly changed.
Let’s give an example first:

import React from 'react';
import ReactDom from 'react-dom';
 
class Time extends React.Component {
  constructor(props) {
    super(props);
 
    // 初始化state
    this.state = {
      hour: 0,
      minute: 0,
      second: 0
    }
  }
  componentDidMount() {
    this.interval = setInterval(() => this.tick(), 1000);
  }
 
  componentWillUnmount() {
    clearInterval(this.interval);
  }
 
  tick() {
    // 计算新时间
    let newSecond, newMinute, newHour;
    let carryMinute = 0, carryHour = 0;
    newSecond = this.state.second + 1;
    if (newSecond > 59) {
      carryMinute = 1;
      newSecond -= 60;
    }
    newMinute = this.state.minute + carryMinute;
    if (newMinute > 59) {
      carryHour = 1;
      newMinute -= 60;
    }
    newHour = this.state.hour + carryHour;
    if (newHour > 59) newHour -= 60;
 
    // 设置新状态
    this.setState({
      hour: newHour,
      minute: newMinute,
      second: newSecond
    });
  }
 
  render() {
    return (
      <div>
        <h1 id="current-time-this-state-hour-this-state-minute-this-state-second">current time: {this.state.hour + ':' + this.state.minute + ':' + this.state.second}</h1>
      </div>
    );
  }
}
ReactDom.render(
  <time></time>,
  document.getElementById('root')
);

This completes a counter, the value changes once a second, let’s explain the code: First, the state is initialized in the constructor, like this:

constructor(props) {
  super(props);
 
  // 在这初始化state
  this.state = {
    ...
  }
}

To change the state, use a built-in function in the React component base class:

this.setState({
  ...
});

Be sure to pay attention to the scope of this before using this function. This in the arrow function points to the external this. This in a normal function points to the function itself.
In addition, the life cycle callbacks of two React components are used here: `

componentDidMount() {
  // React组件被加载到dom中的时候被调用
  ...
}
componentWillUnmount() {
  // React组件从dom中卸载的时候被调用
  ...
}

So the above timer code should not be difficult when the React component is loaded into the dom. Set a timer to update the state every second. When the state is updated, the components in the page will be re-rendered. When the component is unloaded, the timer needs to be cleared. It's that simple.
However, React has a maximum limit for the update frequency of state. Exceeding this limit will cause the performance of page rendering to decrease. You need to be careful not to use setState in high-frequency functions.


The above is the detailed content of Detailed explanation of the usage of props and state attributes in React (code example). For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:segmentfault. If there is any infringement, please contact admin@php.cn delete
React父组件怎么调用子组件的方法React父组件怎么调用子组件的方法Dec 27, 2022 pm 07:01 PM

调用方法:1、类组件中的调用可以利用React.createRef()、ref的函数式声明或props自定义onRef属性来实现;2、函数组件、Hook组件中的调用可以利用useImperativeHandle或forwardRef抛出子组件ref来实现。

如何通过前端优化提升Python网站的访问速度?如何通过前端优化提升Python网站的访问速度?Aug 05, 2023 am 10:21 AM

如何通过前端优化提升Python网站的访问速度?随着互联网的发展,网站的访问速度成为用户体验的重要指标之一。而对于使用Python开发的网站来说,如何通过前端优化提升访问速度是一个必须要解决的问题。本文将介绍一些前端优化的技巧,帮助提升Python网站的访问速度。压缩和合并静态文件在网页中,静态文件如CSS、JavaScript和图片等会占用大量的带宽和加载

确保可维护的WordPress元框:完成前端部分确保可维护的WordPress元框:完成前端部分Aug 27, 2023 pm 11:33 PM

在本系列文章中,我们将回顾一些可用于构建更易于维护的WordPress插件的技巧和策略,并且我们将通过利用选项卡式元框的插件的上下文来实现这一切.在上一篇文章中,我们专门为我们的选项卡实现了功能,并且还实现了第一个textarea,它将用于捕获一些用户输入。对于那些一直关注的人来说,您知道我们只做到了:使选项卡发挥作用引入用户可以与之交互的单个UI元素我们尚未完成清理、验证和保存数据的实际过程,也没有费心介绍其余选项卡的内容。在接下来的两篇文章中,我们将正是这样做的。具体来说,在本文中,我们将继

怎么调试React源码?多种工具下的调试方法介绍怎么调试React源码?多种工具下的调试方法介绍Mar 31, 2023 pm 06:54 PM

怎么调试React源码?下面本篇文章带大家聊聊多种工具下的调试React源码的方法,介绍一下在贡献者、create-react-app、vite项目中如何debugger React的真实源码,希望对大家有所帮助!

React移动端适配指南:如何优化前端应用在不同屏幕上的显示效果React移动端适配指南:如何优化前端应用在不同屏幕上的显示效果Sep 29, 2023 pm 04:10 PM

React移动端适配指南:如何优化前端应用在不同屏幕上的显示效果近年来,随着移动互联网的迅猛发展,越来越多的用户习惯使用手机来浏览网站和使用各种应用。然而,不同手机屏幕的尺寸和分辨率千差万别,这给前端开发带来了一定的挑战。为了让网站和应用在不同屏幕上都有良好的显示效果,我们需要进行移动端适配,并对前端代码进行相应的优化。使用响应式布局响应式布局是一种根据屏幕

深入理解React的自定义Hook深入理解React的自定义HookApr 20, 2023 pm 06:22 PM

React 自定义 Hook 是一种将组件逻辑封装在可重用函数中的方式,它们提供了一种在不编写类的情况下复用状态逻辑的方式。本文将详细介绍如何自定义封装 hook。

React为什么不将Vite作为构建应用的首选React为什么不将Vite作为构建应用的首选Feb 03, 2023 pm 06:41 PM

React为什么不将Vite作为构建应用的首选?下面本篇文章就来带大家聊聊React不将Vite作为默认推荐的原因,希望对大家有所帮助!

7 个很棒且实用的React 组件库(压箱底分享)7 个很棒且实用的React 组件库(压箱底分享)Nov 04, 2022 pm 08:00 PM

本篇文章给大家整理分享7 个很棒且实用的React 组件库,日常开发中经常会用到的,快来收藏试试吧!

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)