美文网首页
React基础-context与prop-types

React基础-context与prop-types

作者: 码枫云 | 来源:发表于2020-01-10 21:24 被阅读0次

context与prop-types用法

prop-types一般限制子组件传进来的props属性的数据类型,限制后对于某些需要固定数据类型的场景可以方便快速检查出错误
context上下文可以把props属性的多级传递或者跨级传递

import React, { Component } from 'react'
import PropTypes from 'prop-types'

class Grandson extends Component{
    static contextTypes = {   /* 3- 组件中需要声明static contextTypes定义接收的数据名和数据类型 */
        arr:PropTypes.array
    }
    render(){
        return(
            <div>
                {this.props.title}
                {this.context.arr} {/* 4- 使用this.context取到数据  */}
            </div>
        )
    }
}

class Child extends Component{
    render(){
        return (
            <div>
                <Grandson title={this.props.title}></Grandson>{/* 子组件再把this.props.title传给孙子组件 */}
            </div>
        )
    }
}
export default class apps extends Component {
    static childContextTypes = { /* 1- 使用Context首先需要在父级组件定义static contextTypes上下文数据类型 */
        arr: PropTypes.array
    }
    getChildContext(){ /* 2- 实现一个实例getChildContext方法.返回一个对象,对象中定义数据的参数 */
        return {
            arr:[1,2,3]
        }
    }
    constructor(p){
        super(p)
        this.state = {
            title:'标题'
        }
    }
    render() {
        return (
            <div>
                <Child title={this.state.title}></Child>{/* 把this.state的title传给子组件 */}
            </div>
        )
    }
}

相关文章

网友评论

      本文标题:React基础-context与prop-types

      本文链接:https://www.haomeiwen.com/subject/hkimactx.html