Home > Web Front-end > JS Tutorial > body text

How to implement component internal communication in React

亚连
Release: 2018-06-14 15:24:48
Original
1587 people have browsed it

This article mainly introduces the internal communication method of components in React data transmission. Now I will share it with you and give you a reference.

1. Overview

After you leave the primary front-end for a while, you will find that you spend less and less time writing styles and more time processing data. Come more and more. The process of processing data is also the process of implementing business logic, which is undoubtedly the most important in the project.

So after learning the front-end framework and understanding the basic syntax, you need to learn how to transfer data.

One of the highlights of Angular design at the beginning is the realization of two-way binding of data. After using Vue for a while, I found that the so-called two-way binding of data, the only application scenario inside the component is the form form (input, textarea , select, radio), and the two-way data binding in this scenario, even if it is not implemented within the framework, it is very simple to implement it yourself. After understanding this, I feel that it was naive to think that React did not implement two-way data binding.

React's data transfer involves two aspects:

  1. Data transfer within the component. Typical application scenarios include how to implement form two-way data binding, How to bind events;

  2. Data transfer between components. Including parent components passing data to child components, child components passing data to parent components, and data passing between sibling components.

This article first discusses the data transfer within the component.

2. Component internal data transfer

React component internal communication is mainly divided into two parts: data display and event processing.

2.1 Data display

The display and update of internal data of components are implemented through state. If you want to use state, you must use ES6 class to define the component. Data updates are discussed in the two-way data binding section, which only discusses displaying initialized data.

If you are familiar with Vue, React's state object is equivalent to Vue's data object

The following is an example of purely displaying data:

class App extends Component {
 constructor(props) {
 super(props);

 // 初始化 state
 this.state = {
  inputValue: "test",
 };
 }

 render() {
 // 注意,在 react 中,DOM 元素是对象,所以使用‘()'包住 
 return (
  <p className="App">
  <p>{this.state.inputValue}</p>
  </p>
 );
 }
}
Copy after login

In a React component defined by class , in addition to the life cycle hook function, the two methods constructor() and render() are also automatically executed. Constructor() is executed first, and while constructor() is executed, data is prepared for render() to render the DOM.

In fact, the constructor() function is the first function called in the component life cycle.

2.2 Events

2.2.1 Similarities and differences with events in DOM

Handling events in React and in DOM Processing events is similar, with two differences:

  1. In React, events are named using camel case naming instead of all lowercase letters;

  2. in React Pass functions directly as event handlers in JSX instead of strings.

The second point is different and has pitfalls, which will be explained in detail later

For example, events in HTML:

<button onclick="activateLasers()">
 Activate Lasers
</button>
Copy after login

Events in React:

// 因为 jsx 中&#39;{}&#39;里面代表函数表达式,
// 所以传递给 onClick 的实际是函数 activateLasers 的函数体部分,
// 因此需要指定 this 指向,不然会报错
<button onClick={activateLasers}>
 Activate Lasers
</button>
Copy after login

2.2.2 Existing pits

Directly passing function as event handler needs to specify the execution environment of the function, that is, it needs to be manually bound to this, otherwise this will be reported as undefined 's fault. See the example below:

class App extends Component {
 constructor(props) {
 super(props);
 this.state = {
  isToggleOn: true,
 };

 // 手动绑定 this
 this.handleClick = this.handleClick.bind(this);
 }

 handleClick() {
 // 如果不在 constructor() 方法中手动绑定 this,直接将其作为事件处理程序 this 为 undefined
 console.log(this);

 this.setState(prevState => ({
  isToggleOn: !prevState.isToggleOn
 }));
 }

 render() {
 return (
  <p className="App">
  <button onClick={this.handleClick}>
   {this.state.isToggleOn ? "on" : "off"}
  </button>
  </p>
 );
 }
}
Copy after login

2.2.3 Why is there a pitfall

The official website of React says that this problem requires JS native syntax to memorize it. In fact, this is not necessarily the case. React actually uses JS syntax. Such an event system was designed under already determined circumstances. If someone must stand up and take the blame, let them give it a 50-50 chance.

1, Problems with JS native grammar

There is such a rule in JS grammar: if the function body of a function (without ()) is assigned to another Variables, the this pointer inside the function body may change. Whether it will change depends on whether the function and the assigned variable are in the same scope (same execution environment), but in actual use, it makes no sense to assign a function to a variable in the same scope. In that case, use that function directly. That's fine, there's no need to assign it to another variable.

This points to a meaningless example that does not change (for convenience of explanation, use the var operator directly):

var fn = function () {
 console.log(this);
};

var a = fn;

fn(); // window
a(); // window
this 指向发生改变的例子:

var fn = function () {
 console.log(this);
};

// 将函数体赋值给一个对象的属性,函数执行时 this 和定义时指向不同
var o = {
 a: fn,
};

fn(); // window
o.a(); // o,即{a:f}
Copy after login

If you want to assign the function body to another variable and at the same time assign the original The this pointer of the function is also assigned together, so you need to bind this during the assignment process, as follows:

var fn = function () {
 console.log(this);
};

// fn 在赋值的同时将内部的 this 打包一块赋值给了 a
var o = {
 a: fn.bind(this),
};

fn(); // window
o.a(); // window
Copy after login

Usually when assigning the function body to a variable, in order to avoid this errors, binding is done The operation of defining the execution environment. A typical example is var bindId = document.getElementById.bind(document)

2, Problems with JSX

Because the DOM elements in JSX It is also an object. Assigning values ​​to the attributes of an element is actually assigning values ​​to the attributes of the DOM element object. See below:

const element = (
 <button onClick={this.handleClick}>click me</button>
);
Copy after login

is equivalent to

const element = {
 type: &#39;button&#39;,
 props: {
 onClick: this.handleClick,
 children: &#39;click me&#39;,
 },
};
Copy after login


. This is actually assigning the function body to an object. attribute, this points to different scenarios when the function is executed and when it is defined. The same as the native syntax, the this pointer has changed. The difference is that no matter what in native JS, this always points to a pointer, while JSX is directly undefined.

So the error of not binding this and reporting undefined cannot be entirely blamed on JS native syntax.

3. 双向数据绑定

通过 state 传递数据加上事件处理程序便能实现数据的双向绑定,其背后的思想是(以 input 为例):初始化时将 state 中预定义的 state a 赋值给 input,当 input 的 value 发生改变时,触发事件处理程序,将改变后的 value 赋值给状态 a ,React 监测到 state 改变时重新调用 render() 方法,即重新渲染组件,达到双向绑定的目的。

class App extends Component {
 constructor(props) {
  super(props);
  this.state = {
   inputValue: "test",
  };
  this.changeInput = this.changeInput.bind(this);
 }

 changeInput(e) {
  // 将改变后的 input 值赋值给 inputValue,通过事件对象 $event.target.value 实现
  this.setState({
   inputValue: e.target.value
  });
 }

 render() {
  // input 改变时触发 changeInput
  return (
   <p className="App">
    <input value={this.state.inputValue} onChange={this.changeInput} />
    <p>{this.state.inputValue}</p>
   </p>
  );
 }
}
Copy after login

这里用到了事件对象,React 的事件对象和 JS 原生事件对象保持一致。

上面是我整理给大家的,希望今后会对大家有帮助。

相关文章:

使用Node.js爬虫如何实现网页请求

使用VueAwesomeSwiper容易出现的问题?

在angular2中有关Http请求原理(详细教程)

在node中如何实现http小爬虫

The above is the detailed content of How to implement component internal communication in React. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template