菜单 学习猿地 - LMONKEY

VIP

开通学习猿地VIP

尊享10项VIP特权 持续新增

知识通关挑战

打卡带练!告别无效练习

接私单赚外块

VIP优先接,累计金额超百万

学习猿地私房课免费学

大厂实战课仅对VIP开放

你的一对一导师

每月可免费咨询大牛30次

领取更多软件工程师实用特权

入驻
339
0

react props-type

原创
05/13 14:22
阅读数 45217

对于组件来说,props是外部传入的,无法保证组件使用者传入什么格式的数据,简单来说就是组件调用者可能不知道组件封装着需要什么样的数据,如果传入的数据不对,可能会导致程序异常,所以必须要对于props传入的数据类型进行校验。

安装校验包 

npm i -S prop-types

 

 

# 在组件中导入

import PropTypes from 'prop-types'

 

# 函数组件

function App(){}

// 验证规则

App.propTypes = {

    prop-name:PropTypes.string

}

 

# 类组件

class App extends Component{

    // 类内部完成 检查

static propTypes = {

   prop-name:PropTypes.string

}

}

 

² 约束类型

https://zh-hans.reactjs.org/docs/typechecking-with-proptypes.html#proptypes

- 类型: arrayboolfuncnumberobjectstring

- React元素类型:element

- 必填项:isRequired

- 特定结构的对象: shape({})

父组件

import React, { Component } from 'react'
import Cmp2fun from './pages/Cmp2fun'
import Cmp2class from './pages/Cmp2class'

export default class App extends Component {
  render() {
    return (
      <div>
        {/* props.children 获取组件内中的数据 插槽 slot */}
        {/* <Cmp2fun a={1} b={2} /> */}
        {/* 默认值 如要传入值,则传入的值为主,默认值为辅 */}
        <Cmp2fun a={1} />
        <Cmp2class a={1} b={2} />

      </div>
    )
  }
}

 

函数组件

import React from 'react';
// 引入proptypes类型检查
import PropTypes from 'prop-types';

// 函数组件
const Cmp2fun = ({ a, b }) => {

  console.log(a + b);

  return (
    <div>

    </div>
  );
}

// 类型检查
Cmp2fun.propTypes = {
  a: PropTypes.number,
  b: PropTypes.number
}

// 默认值
Cmp2fun.defaultProps = {
  b: 1000
}

export default Cmp2fun;

类组件

import React, { Component } from 'react'

// 引入proptypes类型检查
import PropTypes from 'prop-types';

export default class Cmp2class extends Component {

  // 静态方法不能使用this 静态方法属于类的 调用 类.方法名/属性名
  static propTypes = {
    // 类型前面是数字且还是必须填写输入的
    a: PropTypes.number.isRequired,
    b: PropTypes.number
  }
  // 给props添加默认值
  static defaultProps = {
    b: 100
  }

  render() {
    let { a, b } = this.props
    console.log(a + b);
    return (
      <div>

      </div>
    )
  }
}

// 类型检查
/* Cmp2class.propTypes = {
  a: PropTypes.number,
  b: PropTypes.number
} */

// export default Cmp2class

 

发表评论

0/200
339 点赞
0 评论
收藏
为你推荐 换一批