代码之家  ›  专栏  ›  技术社区  ›  Shrey Kejriwal

警告:非布尔属性primary收到true

  •  0
  • Shrey Kejriwal  · 技术社区  · 6 年前

    我为按钮定制了如下组件

    import React, { Component } from 'react';
    import PropTypes from 'prop-types';
    import classNames from 'classnames';
    
    export default class Button extends Component {
      static propTypes = {
        primary: PropTypes.bool,
        block: PropTypes.bool,
        onClick: PropTypes.func.isRequired,
        children: PropTypes.string.isRequired,
        type: PropTypes.oneOf(['button', 'reset', 'submit', null]),
      };
    
      render() {
        const { onClick, type, children, primary, block } = this.props;
        const classes = ['common-button'];
    
        if (primary) {
          classes.push('primary');
        }
    
        if (block) {
          classes.push('block');
        }
    
        return (
          <button className={classNames(classes)} onClick={onClick} type={type} {...this.props}>
            {children}
          </button>
        );
      }
    }
    

    我将此组件用作:

    <Button primary onClick={() => {}}>

    运行代码后,我收到以下控制台警告: 警告:收到 true 对于非布尔属性 primary .

    1 回复  |  直到 6 年前
        1
  •  1
  •   Björn Böing    6 年前

    如果在将属性添加到按钮之前只从属性中提取主要属性,那么应该可以。这可以通过以下方式实现:

    const {primary, ...buttonProps} = this.props;
    
    return (
      <button className={classNames(classes)} onClick={onClick} type={type} {...buttonProps}>
        {children}
      </button>
    );