React's context and props explained

React's context and props explained

1. context

1. Usage scenarios

Imagine a scenario where we want to pass values ​​to descendant components, what should we do?

If you use props to pass it down layer by layer, it will be very cumbersome!

A better way: use context to help us pass data across components

2. Usage steps

  • Call React.createContext() to create two components: Provider (provides data) and Consumer (consumes data).
const { Provider, Consumer } = React.createContext()
  • Use the Provider component as the parent node.
<Provider>
  <div className="App">
    <Child1 />
  </div>
</Provider>
  • Set the value attribute to indicate the data to be passed.
<Provider value="pink">
  • Call the Consumer component to receive data.
<Consumer>
  {data => <span>The data parameter represents the received data-- {data}</span>}
</Consumer>

3. Conclusion

  • If two components are nested in multiple layers, you can use Context to implement component communication
  • Context provides two components: Provider and Consumer
  • Provider component: used to provide data
  • Consumer component: used to consume data

2. Props in-depth

1. The children property

children attribute: represents the child nodes of the component tag. When the component tag has child nodes, props will have this attribute

The children property is the same as normal props, and its value can be anything (text, labels, components, or even functions)

The code is as follows (example):

function Hello(props) {
  return (
    <div>
      Component's child nodes: {props.children}
    </div>
  )
}
<Hello>I am a child node</Hello>

2. Props validation

For components, props is a container for external data, and there is no guarantee of the format of data passed in by component users.

If the format of the incoming data is incorrect, it may cause an error in the component

Key issue: No additional error messages other than syntax error messages

The code is as follows (example):

// Created component function App(props) {
  const arr = props.colors
  const list = arr.map((item, index) => <li key={index}>{item}</li>)
  return (
    <ul>{list}</ul>
  )
}
// When using components <App colors={19} />

Props validation : allows you to specify the type and format of props when creating a component

Purpose : Capture errors caused by props when using components, give clear error prompts, and increase the robustness of components

insert image description here

3. Props validation usage steps

  • Install prop-types (npm i prop-types )
  • Import the prop-types package
  • Use component name.propTypes = {} to add validation rules to component props
  • Validation rules are specified through the PropTypes object
import PropTypes from 'prop-types'
function App(props) {
  return (
    <h1>Hi, {props.colors}</h1>
  )
}
App.propTypes = {
  // The colors property is agreed to be of array type // If the type is incorrect, a clear error will be reported to facilitate error analysis colors: PropTypes.array
}

4. Props validation constraint rules

Common types: number , string , array , bool , func , object

React element type: element

Required: isRequired

Objects of a specific structure: shape({ })

// Common type optionalFunc: PropTypes.func,
// RequiredFunc: PropTypes.func.isRequired,
// Object of specific structure optionalObjectWithShape: PropTypes.shape({
  color: PropTypes.string,
  fontSize: PropTypes.number
})

5. Default props values

Scenario : Pagination component → Number of items displayed per page

Function : Set default values ​​for props, which will take effect when no props are passed in

function App(props) {
  return (
    <div>
      The default value of props is shown here: {props.pageSize}
    </div>
  )
}
// Set default values ​​App.defaultProps = {
  pageSize: 10
}
// Do not pass in the pageSize attribute <App />

Summarize

This article ends here. I hope it can be helpful to you. I also hope that you can pay more attention to more content on 123WORDPRESS.COM!

You may also be interested in:
  • A brief comparison of Props in React
  • Detailed explanation of the use of props in React's three major attributes
  • Talk about the Render Props pattern in React
  • ES6 class chain inheritance, instantiation and react super (props) principle detailed explanation
  • An article to help you understand the principles of React Props

<<:  The relationship between web page production and steamed buns (sharing experience)

>>:  Implementation of CSS scroll bar style settings

Recommend

Sharing tips on using scroll bars in HTML

Today, when we were learning about the Niu Nan new...

JavaScript to achieve magnifying glass effect

This article shares the specific code for JavaScr...

Standard summary for analyzing the performance of a SQL statement

This article will introduce how to use explain to...

How to backup MySQL regularly and upload it to Qiniu

In most application scenarios, we need to back up...

web.config (IIS) and .htaccess (Apache) configuration

xml <?xml version="1.0" encoding=&qu...

Better-scroll realizes the effect of linking menu and content

1. Basic use <!DOCTYPE html> <html lang=...

How to keep running after exiting Docker container

Phenomenon: Run an image, for example, ubuntu14.0...

JavaScript to display hidden form text

This article shares the specific code of JavaScri...

PHP-HTMLhtml important knowledge points notes (must read)

1. Use frameset, frame and iframe to realize mult...

Detailed explanation of MySQL index selection and optimization

Table of contents Index Model B+Tree Index select...

How to hide and remove scroll bars in HTML

1. HTML tags with attributes XML/HTML CodeCopy co...

Use of MySQL DATE_FORMAT function

Suppose Taobao encourages people to shop during D...

Vue implements div wheel zooming in and out

Implement div wheel zooming in and out in Vue pro...