How to use and limit props in react

How to use and limit props in react

The props of the component (props is an object)

Function: Receive data passed to the component Features:

  • You can pass any type of data to a component
  • Props is a read-only object. You can only read the value of the property and cannot modify the object.
  • Note: When using a class component, if you write a constructor, you should pass props to super(), otherwise you will not be able to get it in the constructor.

Props

 <div id="test1"></div>
  <div id="test2"></div>
  <div id="test3"></div>
  <!-- Import react core library -->
  <script src="../js/react.development.js"></script>
  <!-- Introduce react-dom to support react to operate dom -->
  <script src="../js/react-dom.development.js"></script>
  <!-- Introduce babel to convert jsx to js -->
  <script src="../js/babel.min.js"></script>
  <script type='text/babel'>
  // Create component class Person extends React.Component{
    render() {
      console.log(this);
      const{name,age,sex} = this.props
      return(
        <ul>
          <li>Name: {name}</li>
          <li>Gender: {sex}</li>
          <li>Age: {age+1}</li>
        </ul>
      )
    }
  }
  // Render components to the page ReactDOM.render(<Person name="jerry" age={19} sex="男" />,document.getElementById('test1'))
  ReactDOM.render(<Person name="tom" age={18} sex="女" />,document.getElementById('test2'))

  const p = {name:'老刘',age:18,sex:'女'}
  // ReactDOM.render(<Person name={p.name} age={p.age} sex={p.sex} />,document.getElementById('test3'))
  
  ReactDOM.render(<Person {...p} />,document.getElementById('test3'))

  </script>

Limiting props

Be sure to import prop-types.js, otherwise you will get an error

<div id="test1"></div>
  <div id="test2"></div>
  <div id="test3"></div>
  <!-- Import react core library -->
  <script src="../js/react.development.js"></script>
  <!-- Introduce react-dom to support react to operate dom -->
  <script src="../js/react-dom.development.js"></script>
  <!-- Introduce babel to convert jsx to js -->
  <script src="../js/babel.min.js"></script>
  <!-- Introduce prop-types, which is used to restrict component tag attributes. After the introduction, there is one more object PropTypes in the world -->
  <script src="../js/prop-types.js"></script>

  <script type='text/babel'>
  // Create component class Person extends React.Component{
    render() {
      console.log(this);
      const{name,age,sex} = this.props
      return(
        <ul>
          <li>Name: {name}</li>
          <li>Gender: {sex}</li>
          <li>Age: {age+1}</li>
        </ul>
      )
    }
  }
  // Restriction rules Person.propTypes = {
    // Restrict name content to a string isRequired means that the content is required and cannot be omitted name:PropTypes.string.isRequired,
    // Limit sex to string sex: PropTypes.string,
    // Limit age to numeric value age: PropTypes.number,
    // Limit speak to the function speak: PropTypes.func
  }
  Person.defaultProps = {
    sex:'male', // sex default value is male age:18,
    speak: function() {
        return [1];
    }
  }
  // Render components to the page ReactDOM.render(<Person name="jerry" age={19} />,document.getElementById('test1'))
  ReactDOM.render(<Person name="tom" age={18} sex="女" />,document.getElementById('test2'))

  const p = {name:'老刘',age:18,sex:'女'}
  // ReactDOM.render(<Person name={p.name} age={p.age} sex={p.sex} />,document.getElementById('test3'))
  
  ReactDOM.render(<Person {...p} />,document.getElementById('test3'))

  </script>

Vue limits props

We can specify validation requirements for component props, such as these types you know. If a requirement is not met, Vue will warn you in the browser console. This is especially helpful when developing a component that will be used by others.

To customize how props are validated, you can provide an object with validation requirements for the props value instead of an array of strings. For example:

Vue.component('my-component', {
  props: {
    // Basic type checking (`null` and `undefined` will pass any type validation)
    propA: Number,
    // Multiple possible types propB: [String, Number],
    // Required string propC: {
      type: String,
      required: true
    },
    // Numeric propD with default value: {
      type: Number,
      default: 100
    },
    // Object propE with default values: {
      type: Object,
      // Object or array default values ​​must be obtained from a factory function default: function () {
        return { message: 'hello' }
      }
    },
    // Custom verification function propF: {
      validator: function (value) {
        // This value must match one of the following strings return ['success', 'warning', 'danger'].indexOf(value) !== -1
      }
    }
  }
})

When prop validation fails, Vue (in development builds) will generate a console warning.

Note that props are validated before a component instance is created, so instance properties (such as data, computed, etc.) are not available in default or validator functions.

Type checking
type can be one of the following native constructors:

String
Number
Boolean
Array
Object
Date
Function
Symbol

Additionally, type can be a custom constructor that is checked with instanceof. For example, given the following ready-made constructor:

function Person (firstName, lastName) {
  this.firstName = firstName
  this.lastName = lastName
}

You can use:

Vue.component('blog-post', {
  props: {
    author: Person
  }
})

To verify that the value of the author prop is created by new Person.

This is the end of this article about the use and restrictions of props in react. For more information about restrictions on react props, please search for previous articles on 123WORDPRESS.COM or continue to browse the following related articles. I hope you will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • Analysis of Context application scenarios in React
  • Let's talk about my understanding and application of React Context
  • Use react context to implement vue slot function
  • A brief comparison of Props in React
  • Detailed explanation of the use of props in React's three major attributes
  • React's context and props explained

<<:  MySQL exposes Riddle vulnerability that can cause username and password leakage

>>:  How to use Nginx proxy to surf the Internet

Recommend

Summary of HTML horizontal and vertical centering issues

I have encountered many centering problems recent...

Example code for implementing hexagonal borders with CSS3

The outermost boxF rotates 120 degrees, the secon...

Install JDK1.8 in Linux environment

Table of contents 1. Installation Environment 2. ...

Several common methods for passing additional parameters when submitting a form

When submitting a form, you may encounter situatio...

Summary of Linux command methods to view used commands

There are many commands used in the system, so ho...

Zen Coding Easy and fast HTML writing

Zen Coding It is a text editor plugin. In a text ...

A brief discussion on the implementation principle of Webpack4 plugins

Table of contents Preface know Practice makes per...

VMware + Ubuntu18.04 Graphic Tutorial on Building Hadoop Cluster Environment

Table of contents Preface VMware clone virtual ma...

Solution to mysql error when modifying sql_mode

Table of contents A murder caused by ERR 1067 The...

Index Skip Scan in MySQL 8.0

Preface MySQL 8.0.13 began to support index skip ...

MySQL table type storage engine selection

Table of contents 1. View the storage engine of t...