美文网首页
(六)React 组件的 PropTypes与DefaultPr

(六)React 组件的 PropTypes与DefaultPr

作者: 云凡的云凡 | 来源:发表于2020-10-19 12:16 被阅读0次
    接收参数的时候,如何对参数的类型做校验?如何定义参数的默认值,

    PropTypes :对组件接收外部的 props 做一个校验,
    DefaultProps:如果父组件没有传递对应的属性,这时候可以自己在DefaultProps 里定义一个默认值。
    第一步、在组件开头引入

    import PropTypes from 'prop-types';
    
    

    第二步、用组件名调用引入的propTypes 和 defaultProps
    默认值


    image.png
    
     render () {
    //接收父组件传过来的值
        const {content, test} = this.props;
        return (
          <div onClick={this.handleClick}>
            {test}={content}
          </div>
        );
      }
    
    TodoItem.propTypes = {
      test: PropTypes.string.isRequired,
      content: PropTypes.arrayOf (PropTypes.number, PropTypes.string),
      deleteItem: PropTypes.func,
      index: PropTypes.number,
    };
    // 父组件没传 test 的时候给一个默认值
    TodoItem.defaultProps = {
      test: 'hello world',
    };
    

    相关文章

      网友评论

          本文标题:(六)React 组件的 PropTypes与DefaultPr

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