In React, component means "component" in Chinese, which is an encapsulated UI component with independent functions; the content to be displayed is divided into multiple independent parts, and each such part is a component. Components have two important things, one is properties and the other is state. The properties of a component are given to it by the parent component and store the requirements of the parent component for the child component. The properties can be accessed within the component, but they cannot be modified; the state of the component is defined and used by the component itself for storage. The current state of the component. The state of the component can be modified.
#The operating environment of this tutorial: Windows7 system, react18 version, Dell G3 computer.
In React, a component is a UI unit, which is an encapsulated UI component with independent functions. The idea is to divide the content to be displayed into multiple independent parts. Each such part is a component, a bit like a control in Android or iOS.
A component is a part of the page. Various components, large and small, are put together to form a complete page. Just like the puzzle we play, it needs to be spliced together piece by piece to become a complete page. A complete puzzle.
1. Basic components of components
Each component is actually a class when it is extracted from the code. Simple component:
class Greeting extends React.Component { render() { return <h1 id="Hello-nbsp-this-props-name">Hello, {this.props.name}</h1>; } }
As you can see from the above code, components can define methods just like general classes. For components, the render() method is very important (must be implemented), and it is in this method that the interface of the component is returned. In the render() method, JSX is used to define the component's interface. The render() method will be described in further detail later.
In addition, components have two important things, one is properties (props) and the other is state (state). Simply put, the properties of a component are given to it by the parent component (components can be nested). What is stored is the parent component's requirements for the child component. The properties can be accessed (used) within the component, but they cannot be modified. ;The state of the component is defined and used by the component itself. It is used to store the current state of the component. The state of the component can be modified.
2. Component life cycle
The life cycle of a component can be roughly divided into three stages: display (mounting), refresh (updating), and disappear (unmounting) ).
In each stage, several steps are subdivided.
1. Display stage (Mounting)
is the stage when components are created and inserted into the view. The following methods are executed in sequence:
- constructor(props)
It will be called when the component is created. In this method, you can access the property object props passed by the parent component. If you want to override this method, you must remember to write super(props) first; otherwise, the attributes cannot be accessed inside this component (the content of the attributes will be detailed later).
- componentWillMount()
- render()
- componentDidMount()
2. Refresh phase ( Updating)
When the component's properties (props) and state (state) change, the component will be triggered to refresh. The following method is executed at once:
- componentWillReceiveProps (nextProps)
Will be called when the properties of the component change. In this method, nextProps is the new property. If you want to update the state within this method, you should first ensure that the current value and the new value of the attribute are different before refreshing the state.
- shouldComponentUpdate()
This method returns true or false to determine whether the render() method of the component will be called.
- componentWillUpdate()
- render()
- componentDidUpdate()
3. Disappearance phase ( Unmounting)
After the component is removed, it will enter the disappearing stage and execute the following method:
- componentWillUnmount()
3. Properties, status and methods of components
Inside a component, to access its own properties, status and methods, you generally need to use the this keyword to express the meaning of this component.
1. Component methods
The format for accessing component methods: this.methodName(param1, param2, …)
For example, a method is defined inside the component:
_method() { console.log(‘method call ! ~~~~’); }
To call it: this._method();
2. Component properties
上面提到,组件的属性,是由父组件给的,从意义上理解,组件的属性用来存储父组件对子组件的要求。
访问组件的属性格式: this.props.propertyName
这里看到,与访问组件的方法不同,这里没有直接在this后就直接跟属性名,中间多了一个props。这个props其实是一个属性对象,上面我们提到属性是父组件给的,那么这个props对象就相当于把父组件给的所有的属性都封装起来,一个props对象像这样:
{ property1:value1, property2:value2, … }
注意,在使用react的时候会经常遇到用这种形式表示的对象,也就是一个花括号内包含若干对属性名和属性值。
访问组件的属性的例子:
例如组件有一个属性height,那么要访问它: this.props.height;
虽然属性不能修改,但我们能给组件属性一个默认值,也就是说,当父组件没有给该属性赋值的时候,使用的一个默认值。
例如给组件CustomButton定义默认属性:
CustomButton.defaultProps = { color: 'blue' };
另外还可以给组件的属性指定类型,在开发模式下这个如果父组件设置的属性不符合子组件设定的类型的话,会输出警告,在生产模式下就不会对类型进行检查,例如,设定CustomButton组件的color属性的类型为字符:
CustomButton.propTypes = { color: React.PropTypes.string };
3. 组件的状态
组件的状态,就是用来存储组件的当前状态。
访问状态的格式: this.state.propertyName
例如,组件有个属性height,那么要访问它对应的状态: this.state.height;
与组件的属性类似,这里也没有直接在this后跟属性名,中间多了个state。类似的,state也是一个状态对象,把所有属性对应的状态封装起来。既然是对象,当然也可以使用上面说的“花括号内包含若干对属性名和属性值”的形式来表示,像这样:
{ property1:value1, property2:value2, … }
上面提到,属性是父组件给的,不可修改,但状态可以修改。由于状态是一个对象,因此修改状态,就是给this.state赋予一个新的对象:
this.state = { propertyName1:newValue1, propertyName2:newValue2, … };
或者使用setState()方法,这个方法会将新的、旧的状态合并,因此只需要填入有变化的状态就好,
this.setState({ propertyName1:newValue1, propertyName2:newValue2, … });
例如,修改一个组件的两个状态height和width分别为100和200:
this.state = { height:100,width:200, };
或
this.setState({ height:100, width:200, });
四、组件的render()方法
上面提到,render()方法是专门用来返回组件界面的。从组件的生命周期可以看出,在组件第一次加载的时候,或者组件的props或state有变化的时候,render()方法都会被调用,也就是说这两种情况下,组件会重画它的界面,因此在render()方法中尽量只做有关界面的事情。
组件的界面也是由一个或多个其他的组件组成的,比如View、Button、Text等等。需要注意的是,如果当多个子组件都需要使用同一个状态(状态可能会改变)的时候,为了减少对状态(属性)的访问次数,建议在render()方法中,先用一个变量存储该状态的当前值,然后在各个组件中使用这个变量,而不是在各个组件中多次访问这个状态。
例如,这里组件Text、Input、Image都是用到了this.state.value,推荐的写法是:
render() { const value = this.state.value; return ( <View> <Text>{value}</Text> <Input value={value} onChange={this.handleChange} /> <Image source = {{ uri : value }}/> </View> ); }
在上面的例子当中,return()方法内部是由的是JSX,ReactNative支持的表示界面的一种语法,类似于XML或者HTML。这个可以去查查看。
这个例子里,组件使用的都是this.state.value。这里可能就存在疑惑,在组件中什么时候应该用props,什么时候应该用state。下面看,属性和状态的使用场景。
五、属性和状态的使用场景
在组件中应该用props还是state,取决于这个信息是来自于组件内部还是来自于组件外部。什么意思呢?
例如,自定义一个组件CustomView(如下图)。CustomView包括一个输入框组件Input和一个文本框组件CustomText。现在要求CustomText显示的文本随Input中输入的内容变化(输入什么就显示什么)。
对于组件CustomView,其子组件CustomText的要显示的文本来自于子组件Input,都是在CustomView的内部,因此CustomView可以用this.state.value来存储输入框的内容,然后CustomText就显示this.state.value。
那么站在组件CustomText的角度,假定CustomText内部包含一个Text组件,实际上文本是由Text组件显示的(如下图):
为了满足组件CustomText的文本随输入框的内容改变,就要求CustomView要将输入框的内容传到CustomText内部,这样CustomText的子组件Text才可以访问到。这就需要用到属性。如果CustomView通过属性textFromInput传给CustomText的话,在CustomText内部,就可以通过this.props.textFromInput访问到。
所以CustomView的render()方法应该是这样的:
render(){ var value = this.state.value; return( <CustomText textFromInput = {value}/> <Input onChange = {this._inputValueChange}/> ); }
CustomText的render()方法应该是这样的:
render(){ return( <Text>{this.props.textFromInput}</Text> ); }
这时候,只要实现每次输入内容变化的时候更新状态value,就可以实现CustomText的内随输入内容变化。上面onChange指向_inputValueChange方法,于是实现该方法:
this._inputValueChange(e){ this.setState({ value:e.target.value; }); }
The above is the detailed content of What is the component of react?. For more information, please follow other related articles on the PHP Chinese website!

To integrate React into HTML, follow these steps: 1. Introduce React and ReactDOM in HTML files. 2. Define a React component. 3. Render the component into HTML elements using ReactDOM. Through these steps, static HTML pages can be transformed into dynamic, interactive experiences.

React’s popularity includes its performance optimization, component reuse and a rich ecosystem. 1. Performance optimization achieves efficient updates through virtual DOM and diffing mechanisms. 2. Component Reuse Reduces duplicate code by reusable components. 3. Rich ecosystem and one-way data flow enhance the development experience.

React is the tool of choice for building dynamic and interactive user interfaces. 1) Componentization and JSX make UI splitting and reusing simple. 2) State management is implemented through the useState hook to trigger UI updates. 3) The event processing mechanism responds to user interaction and improves user experience.

React is a front-end framework for building user interfaces; a back-end framework is used to build server-side applications. React provides componentized and efficient UI updates, and the backend framework provides a complete backend service solution. When choosing a technology stack, project requirements, team skills, and scalability should be considered.

The relationship between HTML and React is the core of front-end development, and they jointly build the user interface of modern web applications. 1) HTML defines the content structure and semantics, and React builds a dynamic interface through componentization. 2) React components use JSX syntax to embed HTML to achieve intelligent rendering. 3) Component life cycle manages HTML rendering and updates dynamically according to state and attributes. 4) Use components to optimize HTML structure and improve maintainability. 5) Performance optimization includes avoiding unnecessary rendering, using key attributes, and keeping the component single responsibility.

React is the preferred tool for building interactive front-end experiences. 1) React simplifies UI development through componentization and virtual DOM. 2) Components are divided into function components and class components. Function components are simpler and class components provide more life cycle methods. 3) The working principle of React relies on virtual DOM and reconciliation algorithm to improve performance. 4) State management uses useState or this.state, and life cycle methods such as componentDidMount are used for specific logic. 5) Basic usage includes creating components and managing state, and advanced usage involves custom hooks and performance optimization. 6) Common errors include improper status updates and performance issues, debugging skills include using ReactDevTools and Excellent

React is a JavaScript library for building user interfaces, with its core components and state management. 1) Simplify UI development through componentization and state management. 2) The working principle includes reconciliation and rendering, and optimization can be implemented through React.memo and useMemo. 3) The basic usage is to create and render components, and the advanced usage includes using Hooks and ContextAPI. 4) Common errors such as improper status update, you can use ReactDevTools to debug. 5) Performance optimization includes using React.memo, virtualization lists and CodeSplitting, and keeping code readable and maintainable is best practice.

React combines JSX and HTML to improve user experience. 1) JSX embeds HTML to make development more intuitive. 2) The virtual DOM mechanism optimizes performance and reduces DOM operations. 3) Component-based management UI to improve maintainability. 4) State management and event processing enhance interactivity.


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

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

Dreamweaver CS6
Visual web development tools

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

Dreamweaver Mac version
Visual web development tools