React 父传子


先展示父组件

import React, { Component } from 'react'

import Banner from "../Banner/Banner"
export default class Header extends Component {
    constructor(props){
        super(props);
        this.state={
            title:'我是标题'
        }
    }
    render() {
        const{title} = this.state
        return (
            
//子组件的复用

我是标题

) } }

再展示子组件

import React, { Component } from 'react'

export default class Banner extends Component {
    render() {
        const {name,age,height} = this.props   //通过this.props解构拿到数据
        return (
            
子组件展示的信息 姓名:{name}, 年龄:{age}, 身高:{height},
) } }

通过this.props解构后拿到name,age,height的数据。

下面是通过函数式组件:父传子

import React from 'react'

export default function Hanshu(props) {
    const {name,age,height} = props
    return (
        
你好,我叫{name},今年{age}岁,{height}cm。
) }

不需要this。直接传入props。解构后拿到数据

父传子的参数验证:propTypes

Banner.propTypes = {
            name:PropTypes.string.isRequired,  //加上isRequired说明必须传的值
            age:PropTypes.number,
            names:PropTypes.array
        }

不传值的情况,展示默认值 defaultProps