React study notes five-props

This article is a study note I wrote when I was learning React. I will record and share it here. This is the fifth article, which mainly introduces props in react.

Table of contents

1.Basic use of props

 2.Batch delivery of props

2.1 Review of spread operators

2.1.1 Spread operator in array

 2.1.2 Spread operator in function

 2.1.3 Use expansion syntax when constructing literal objects

2.2 Expansion operator and props 

3. Limit props

4.Abbreviation of props

5. Constructors and props in class components

6. Functional components and props

6.1 Using props in functional components

 6.2 Limiting props in functional components

7. Summary of props


1.Basic use of props

Let's first write a small case to render a person's name, gender and age on the page in the form of li. We need to render multiple people.

At this time, I first wrote the class component, and wrote const {name, age, sex} = this.props in the render function, deconstructing and assigning values ​​​​to the props in the instance, so that we can render the name and age in the props when building a virtual dom. and sex.

Finally, in ReactDOM.render , when we write the component name, we pass the name, age and sex into the component.

Just like <Person name='Zhang San' sex='Male' age='18'/> . In this way, the three data of name, sex and age exist in the props attribute in the instance created by our component. When the render function generates the virtual dom, the data in the props will be directly obtained.

code show as below:

<!-- 准备好容器 -->
    <div id="test1"></div>
    <div id="test2"></div>
    <div id="test3"></div>
<script src="https://cdn.staticfile.org/react/16.4.0/umd/react.development.js"></script>
    <script src="https://cdn.staticfile.org/react-dom/16.4.0/umd/react-dom.development.js"></script>
    <script src="https://cdn.staticfile.org/babel-standalone/6.26.0/babel.min.js"></script>

    <script type="text/babel">
        class Person extends React.Component {
            render(){
                console.log(this);//打印this指向的实例对象,查看props属性
                const {name,age,sex} = this.props//解构赋值
                return(//构建虚拟dom
                    <ul>
                        <li>姓名:{name}</li>
                        <li>性别:{sex}</li>
                        <li>年龄:{age}</li>    
                    </ul>
                )
            }
           
        }
        //分别渲染dom到三个容器内
        ReactDOM.render(<Person name='张三' sex='男' age='18'/>, document.getElementById('test1'))
        ReactDOM.render(<Person name='李四' sex='女' age='19'/>, document.getElementById('test2'))
        ReactDOM.render(<Person name='王五' sex='男' age='20'/>, document.getElementById('test3'))
    </script>

The effect is as follows:

 2.Batch delivery of props

2.1 Review of spread operators

When learning batch transfer of props, we must first review the expansion operator, which is the three-dot operator.

2.1.1 Spread operator in array

For the following two arrays, the spread operator can expand and display each item in an array, or it can splice two arrays together into a new array.

code show as below:

let arr1 = [1, 3, 5, 7, 9]
let arr2 = [2, 4, 6, 8, 10]
console.log(...arr1);//展开数组
let arr3 = [...arr1, ...arr2]
console.log(arr3);//拼接数组

The effect is as follows:

 2.1.2 Spread operator in function

We write a summation function and use the spread operator when passing parameters. First, print the parameters and find that when passed using the spread operator, the passed parameters will become an array. Then we run the function normally and the output results ensure that there is no problem with the summation function of the function.

code show as below:

function sum(...numbers) {
            console.log(numbers);
            return numbers.reduce((preValue, currentValue) => {
                return preValue + currentValue
            })
        }
        console.log(sum(1, 2, 3, 4));

The effect is as follows:

 2.1.3 Use expansion syntax when constructing literal objects

Let’s first write code like this:

let person = {name:'tom', age:18}
console.log(...person);//报错。展开运算符不可以展开对象

The effect is as follows:

 Therefore, the spread operator cannot spread objects.

But look at the code below:

 let person = {name:'tom', age:18}
 let person2 = {...person}
 console.log(person2);

The effect is as follows:

 We use the spread operator to expand person and assign it to person2 to implement deep copy. Even if we change the content in person, the content of person2 will not change.

The code is as follows: Let’s write another person3.

 let person3 = {...person,name:'jack',address:'地球'}
        console.log(person3);

The effect is as follows: person3 is the merge of person and new attributes, and the consistent attributes are overwritten.

2.2 Expansion operator and props 

Still in the above case, we try to use the spread operator inside the component in ReactDOM.render.

The code is as follows: We directly write an object to store name, sex and age, and assign it to p. In the component props in ReactDOM.render, we use the expansion operator to pass in the name, sex and age data in batches at one time, which is simple and fast.

ReactDOM.render(<Person name='李四' sex='女' age={19} />, document.getElementById('test2'))
       
const p = { name:'王五', sex:'男', age:19 }
ReactDOM.render(<Person {...p}/>, document.getElementById('test3'))

3. Limit props

In the above basic case, if we limit the types of name, sex and age to string, string and number respectively, and stipulate that the name attribute cannot be empty, and sex and age have default values, what should we do?

code show as below:

First introduce the propTypes library. This dependent package is the package required to limit props.

 <!-- 新引入的库,用于限定props传入值的类型,propTypes -->
    <script src="https://cdn.bootcss.com/prop-types/15.6.1/prop-types.js"></script>

We then use Person.propTypes to set type qualification and non-nullability for various properties within Person.

Use Person.defaultProps to set default values ​​for properties within Person.

Note that when setting attributes, string and number types are all lowercase, and function types are written as func.

//在引入相应的依赖包后,才能使用本代码对数据类型进行限定
        Person.propTypes = {//为Person的数据设置类型限定
            name:PropTypes.string.isRequired,//限定name必须为string类型,并且不得为空
            sex:PropTypes.string,//限制sex为string类型
            age:PropTypes.number,//限定age为number类型
            speak:PropTypes.func//限定speak为function类型
        }
        Person.defaultProps = {//为Person的数据设置默认数据
            sex:'性别未知',//为sex设置默认值
            age:18//设置age默认值为18
        }
        //分别渲染dom到三个容器内
        ReactDOM.render(<Person name='张三' sex='男' age={18} speak={speak}/>, document.getElementById('test1'))
        ReactDOM.render(<Person name='李四' sex='女' age={19}/>, document.getElementById('test2'))
        ReactDOM.render(<Person name='王五' sex='男' age={19}/>, document.getElementById('test3'))

        function speak() {
            console.log('我说话了');
        }

After writing, you can try to violate the type restrictions and pass in different types of values ​​​​for the attributes. At this time, the console will clearly point out the error due to different data types.

4.Abbreviation of props

The code is as follows: We transfer the code for setting type restrictions on data and setting default data, plus the static keyword, into the class that creates the component. Be careful not to write it into the render function. In this way, the props code part is placed inside the component, which is relatively concise and standardized.

//创建组件
        class Person extends React.Component {
            static propTypes = {//为Person的数据设置类型限定
                name: PropTypes.string.isRequired,//限定name必须为string类型,并且不得为空
                sex: PropTypes.string,//限制sex为string类型
                age: PropTypes.number,//限定age为number类型
                speak: PropTypes.func//限定speak为function类型
            }
            //指定默认标签属性值
            static defaultProps = {//为Person的数据设置默认数据
                sex: '性别未知',//为sex设置默认值
                age: 18//设置age默认值为18
            }
            render() {
                console.log(this);//打印this指向的实例对象,查看props属性
                const { name, age, sex } = this.props//解构赋值
                return (//构建虚拟dom
                    <ul>
                        <li>姓名:{name}</li>
                        <li>性别:{sex}</li>
                        <li>年龄:{age}</li>
                    </ul>
                )
            }

        }

5. Constructors and props in class components

What is the role of constructor in class components? Let’s take a look at the explanation from react’s official website:

Generally, in React, constructors are only used in the following two situations:

        1. Initialize the internal state by assigning a value object to this.state

        2. Bind the instance to the event handling function.

In fact, when writing class components, you don't need to write a constructor. If you write a constructor, you don’t need to receive the props parameter, and you don’t need to write it in super(), but if so, console.log('constructor', this.props); this line of code will print undefined, which is There is no way to get the value through instance.props in the constructor.

code show as below:

constructor(props){
      console.log(props);
      super(props)
      console.log('constructor',this.props);
}

result:

 When not receiving props:

constructor(){ 
     super()
     console.log('constructor',this.props);
}

result:

 Therefore, whether the constructor receives props and whether to pass props to the super keyword depends on whether you want to access props through this in the constructor. But this scenario is extremely rare. If there is no need for this, the constructor can be omitted directly. If possible, save it.

6. Functional components and props

For the three major attributes of the instance, functional components cannot use state and ref, but they can use props because they can receive parameters.

6.1 Using props in functional components

We receive parameter props directly in the functional component and render the component to the interface in ReactDOM.render(<Person name='Zhang San' sex='male' age={18} />, document.getElementById('test1')) When receiving parameters, name='Zhang San' sex='Male' age={18}, these three incoming data will be automatically saved to the props in the functional component and exist in the form of objects. After we use destructuring assignment to deconstruct the props, we can directly use them in the virtual dom.

code show as below:

function Person(props) {
            const { name, age, sex } = props
            return (//构建虚拟dom
                <ul>
                    <li>姓名:{name}</li>
                    <li>性别:{sex}</li>
                    <li>年龄:{age}</li>
                </ul>
            )
        }
        //渲染组件到界面
        ReactDOM.render(<Person name='张三' sex='男' age={18} />, document.getElementById('test1'))

The effect is as follows:

 6.2 Limiting props in functional components

Similar to class components, we write component name.propTypes and component name.defaultProps to limit the data type of props and set default data. After writing, you can pass in any type of data, or no data is written. Look at the output of the console and find that there is no problem with the restrictions and default settings.

code show as below:

function Person(props) {
            const { name, age, sex } = props
            return (//构建虚拟dom
                <ul>
                    <li>姓名:{name}</li>
                    <li>性别:{sex}</li>
                    <li>年龄:{age}</li>
                </ul>
            )
        }
        Person.propTypes = {//为Person的数据设置类型限定
            name: PropTypes.string.isRequired,//限定name必须为string类型,并且不得为空
            sex: PropTypes.string,//限制sex为string类型
            age: PropTypes.number,//限定age为number类型
        }
        Person.defaultProps = {//为Person的数据设置默认数据
            sex: '性别未知',//为sex设置默认值
            age: 18//设置age默认值为18
        }
        //渲染组件到界面
        ReactDOM.render(<Person name='张三'/>, document.getElementById('test1'))

7. Summary of props

understand:

1. Each component object will have props attributes.

2. All attributes of the component tag are reported to the props attribute.

effect:

1. Pass changing data from outside the component to within the component through label attributes.

2. Note: Do not modify props data inside the component.

Guess you like

Origin blog.csdn.net/zhangawei123/article/details/130751307