prop-types 是用来约束 react 传参
不加约束 穿数字类型的时候会被视为 String 类型 出现奇奇怪怪的东西
函数约束
导入 import PropType from 'prop-types'
函数的默认值,不设置初始化会报错
News.defaultProps = { age: 10, }
函数的类型约束
News.propTypes = { age: PropType.number.isRequired, }
import React, {useState} from "react";
import PropType from 'prop-types'
import Textconst from "../../Textcontext/textcontext";
import {Link, useNavigate, useRoutes} from "react-router-dom";
import router from "../../router/router";
import {gou} from "../../App";
// export default class News extends React.Component{
// render() {
// return <div >新闻</div>
// }
// }
export default function News (props) {
return (<div> 数据参数</div>);
}
News.defaultProps = {
age: 10,
}
News.propTypes = {
age: PropType.number.isRequired,
}
类组件约束
static 会在类组件本身加载并不会被继承走
static propTypes = { age: PropType.number } // 如果传递过来 proptype会拿着默认值去渲染 static defaultProps = { age: 10 }
import {Table} from "antd";
import PropType from 'prop-types'
import React, {Component, createContext} from 'react'
import { login } from '../api/shoop'
const {Provider,Consumer} = React.createContext();
class Shoop extends Component{
state = {
age:20,
dataSource :[
{
key: '1',
name: '胡彦斌',
age: 32,
address: '西湖区湖底公园1号',
},
{
key: '2',
name: '胡彦祖',
age: 42,
address: '西湖区湖底公园1号',
},
],
columns:[
{
title: '姓名',
dataIndex: 'name',
key: 'name',
},
{
title: '年龄',
dataIndex: 'age',
key: 'age',
},
{
title: '住址',
dataIndex: 'address',
key: 'address',
},
]
}
//限制传值或者必传必须传值方式
static propTypes = {
age: PropType.number
}
// 如果传递过来 proptype会拿着默认值去渲染
static defaultProps = {
age: 10
}
changeValue = () => {
this.setState({age:100})
}
getvalue = () => {
login().then((res) => {
console.log(res,"dfkdjkfgdjgfjghfjghfjghfgjhfjghfkhgfjdghfhgjfhgfjghfjghfghjghfgh")
})
}
// 组件创建的时候
componentDidMount() {
console.log("组件创建")
this.getvalue()
}
shouldComponentUpdate(nextProps, nextState, nextContext) {
console.log(nextProps)
console.log(nextState)
console.log(nextContext)
return true
}
// 组件渲染的时候出触发
componentDidUpdate(prevProps, prevState, snapshot) {
console.log(this.props,"组件渲染的时候出触发")
console.log(prevProps,"上次的props状态")
console.log(prevState,"上次的props状态")
console.log(snapshot,"weihz")
}
// 组件卸载
componentWillUnmount() {
console.log("组件卸载了")
}
componentDidCatch(error, errorInfo) {
}
// 初始化
constructor(props) {
// 在初始化获取数据
console.log("进入数据初始化")
console.table(props)
super(props);
}
// 渲染区域
render(){
return <div>
<button onClick={this.changeValue}>点击改变数据</button>
<Provider value="pink"> <Table dataSource={this.state.dataSource} columns={this.state.columns} /> </Provider>
</div>
}
}
export default Shoop;