警告:对于非布尔属性主变量,接收为true

时间:2018-12-31 09:28:53

标签: reactjs

我已经为按钮制作了自定义组件,如下所示:

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 个答案:

答案 0 :(得分:2)

如果在将道具添加到按钮之前简单地从道具中提取主要属性,那应该没问题。这可以通过以下方式实现:

const {primary, ...buttonProps} = this.props;

return (
  <button className={classNames(classes)} onClick={onClick} type={type} {...buttonProps}>
    {children}
  </button>
);