Interviewer: What are the ways of communication between components in React?

Interviewer: What are the ways of communication between components in React?

[[409233]]

This article is reprinted from the WeChat public account "JS Daily Question", the author is Huihui. Please contact the JS Daily Question public account to reprint this article.

1. What is

We can split the communication between components into two words:

  • Components
  • Communications

Looking back at the Vue series of articles, components are one of the most powerful features of Vue, and componentization is also the core idea of ​​React.

Compared with Vue, React's components are more flexible and diverse, and can be divided into many types of components in different ways.

Communication refers to the process by which a sender transmits information to a receiver in a certain format through a certain medium in order to achieve a certain purpose. In a broad sense, any information traffic is communication.

Communication between components means that components transmit information in some way to achieve a certain purpose.

2. How to communicate

There are many ways to transfer components, which can be divided into the following according to the sender and receiver:

  • Passing from parent component to child component
  • Child component passes to parent component
  • Communication between sibling components
  • Passing from parent component to descendant component
  • Non-relational component transfer

Passing from parent component to child component

Since the data flow of React is one-way, passing from parent component to child component is the most common way

When the parent component calls the child component, it only needs to pass parameters in the child component tag, and the child component can receive the parameters passed by the parent component through the props attribute

  1. function EmailInput(props) {
  2. return (
  3. <label>
  4. Email: <input value={props.email} />
  5. </label>
  6. );
  7. }
  8.  
  9. const element = <EmailInput email= "[email protected]" />;

Child component passes to parent component

The basic idea of ​​​​child component communication with parent component is that the parent component passes a function to the child component, and then gets the value passed by the child component through the callback of this function

The corresponding code of the parent component is as follows:

  1. class Parents extends Component {
  2. constructor() {
  3. super();
  4. this.state = {
  5. price: 0
  6. };
  7. }
  8.  
  9. getItemPrice(e) {
  10. this.setState({
  11. price: e
  12. });
  13. }
  14.  
  15. render() {
  16. return (
  17. <div>
  18. <div>price: {this.state.price}</div>
  19. {/* Pass a function into the child component */}
  20. <Child getPrice={this.getItemPrice.bind(this)} />
  21. </div>
  22. );
  23. }
  24. }

The corresponding code of the subcomponent is as follows:

  1. class Child extends Component {
  2. clickGoods(e) {
  3. // Pass the value into this function
  4. this.props.getPrice(e);
  5. }
  6.  
  7. render() {
  8. return (
  9. <div>
  10. <button onClick={this.clickGoods.bind(this, 100)}>goods1</button>
  11. <button onClick={this.clickGoods.bind(this, 1000)}>goods2</button>
  12. </div>
  13. );
  14. }
  15. }

Communication between sibling components

If the data is transferred between sibling components, the parent component acts as an intermediate layer to achieve data intercommunication.

  1. class Parent extends React.Component {
  2. constructor(props) {
  3. super(props)
  4. this.state = { count : 0}
  5. }
  6. setCount = () => {
  7. this.setState({ count : this.state. count + 1})
  8. }
  9. render() {
  10. return (
  11. <div>
  12. <SiblingA
  13. count = { this.state.count }
  14. />
  15. <SiblingB
  16. onClick={this.setCount}
  17. />
  18. </div>
  19. );
  20. }
  21. }

Passing from parent component to descendant component

It is a common thing for a parent component to pass data to its descendant components, just like global data.

Using context provides a way for components to communicate with each other, so that data can be shared and other data can read the corresponding data.

Create a context by using React.createContext

  1. const PriceContext = React.createContext( 'price' )

After the context is successfully created, the Provider component exists under it to create the data source, and the Consumer component is used to receive data. The usage examples are as follows:

The Provider component uses the value attribute to pass data to descendant components:

  1. <PriceContext.Provider value={100}>
  2. </PriceContext.Provider>

If you want to get the data passed by the Provider, you can receive it through the Consumer component or use the contextType property, which are as follows:

  1. class MyClass extends React.Component {
  2. static contextType = PriceContext;
  3. render() {
  4. let price = this.context;
  5. /* Perform rendering based on this value */
  6. }
  7. }

Consumer component:

  1. <PriceContext.Consumer>
  2. { /* This is a function */ }
  3. {
  4. price => <div>price:{price}</div>
  5. }
  6. </PriceContext.Consumer>

Non-relational component transfer

If the relationship between components is complex, it is recommended to manage the data in a global resource to achieve communication, such as redux. The use of redux will be introduced in detail later.

Conclusion

Since React is a one-way data flow, the main idea is that components will not change the data they receive, but only listen for changes in the data. When the data changes, they will use the new value they received instead of modifying the existing value.

Therefore, it can be seen that during the communication process, the storage location of the data is stored in the parent location

References

https://react.docschina.org/docs/context.html

<<:  A brief history of the development of the iSCSI storage protocol

>>:  Viavi: Global 5G deployments to grow by more than 20% in 2021

Recommend

The impact of 5G technology on these 20 industries

5G, a new era product developed in response to th...

How Fiber Optic Cable Helps Data Centers Save Money

In a data center, reliable fiber optic cables are...

Why restarting the router frequently makes WiFi faster

Using WiFi to surf the Internet has become an ind...

RackNerd: San Jose AMD Ryzen+DDR4+NVMe series KVM starts at $14.18 per year

Previously, we have shared information about the ...

How will 6G develop in the future?

In the past two years, with the gradual populariz...

Fiberia.io: $2.9/month KVM-4GB/50GB/2TB/Netherlands data center

Fiberia.io is a new website, from the same compan...

2019: 5G takes center stage, changing lives and spreading across industries

Every upgrade of communication technology brings ...

Bryan to launch fiber optic internet service

The city of Bryan, Texas, recently announced that...