我已经为按钮制作了自定义组件,如下所示:
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
。
答案 0 :(得分:2)
如果在将道具添加到按钮之前简单地从道具中提取主要属性,那应该没问题。这可以通过以下方式实现:
const {primary, ...buttonProps} = this.props;
return (
<button className={classNames(classes)} onClick={onClick} type={type} {...buttonProps}>
{children}
</button>
);