React中使用 PropTypes 进行类型检查

官方文档学习链接:https://zh-hans.reactjs.org/docs/typechecking-with-proptypes.html

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

class TodoItem extends Component {
  constructor (props) {
    super(props)
    this.handleClick = this.handleClick.bind(this)
  }

  render() {
    const { content, test } = this.props
    return (
        <li onClick={this.handleClick}>
          { test } - { content }
          {/* { this.props.content } */}
        </li>
    )
  }

  handleClick () {
    const { deleteItem, index } = this.props
    deleteItem(index)
    // this.props.deleteItem(this.props.index)
  }
}

// PropTypes规定父组件传递值的类型
TodoItem.propTypes = {
  // isRequired 设置属性为必传
  test: PropTypes.string.isRequired,
  // arrayOf 可以指定值为多种类型,可以指定一个数组由某一类型的元素组成
  content: PropTypes.arrayOf(PropTypes.number, PropTypes.string),
  // content: PropTypes.string,
  deleteItem: PropTypes.func,
  index: PropTypes.number
}
// 若父组件没有给子组件传值(test),可以通过defaultProps设置默认值
TodoItem.defaultProps = {
  test: 'hello world'
}

export default TodoItem

猜你喜欢

转载自www.cnblogs.com/nayek/p/12360387.html