首页 > 解决方案 > 如何在 React 中导入 Bootstrap 组件?

问题描述

我正在尝试从Reactbootstrapreactstrap在 React 中集成复选框。我遇到了一个常见错误,查看了相关帖子,仍然无法弄清楚。如何解决此错误:

错误元素类型无效:需要一个字符串(对于内置组件)或一个类/函数(对于复合组件),但得到:未定义。您可能忘记从定义组件的文件中导出组件,或者您可能混淆了默认导入和命名导入。

错误来源

问题应该在这两行中,我不确定它是什么。

import { InputGroup, InputGroupAddon, InputGroupText } from 'reactstrap';
import FormControl from 'react-bootstrap/FormControl';

如果我们删除这些行和下面复制的 HTML,它不会给出任何错误。

HTML

          <div>
            <InputGroup className="mb-3">
              <InputGroup.Prepend>
                <InputGroup.Checkbox aria-label="Checkbox for following text input" />
              </InputGroup.Prepend>
              <FormControl aria-label="Text input with checkbox" />
            </InputGroup>
            <InputGroup>
              <InputGroup.Prepend>
                <InputGroup.Radio aria-label="Radio button for following text input" />
              </InputGroup.Prepend>
              <FormControl aria-label="Text input with radio button" />
            </InputGroup>
          </div>

演示

[谢谢!我是 React 的新手。]

标签: javascripthtmlcssreactjsreact-bootstrap

解决方案


prependaddonTypeInputGroupAddOn 或 InputGroupButton 的属性之一。它不是InputGroup导入的属性。 InputGroup.Prepend是未定义的,这就是 React 抱怨的原因。

根据reactstrap docs,你想要这个:

InputGroupAddOn.propTypes = {
  tag: PropTypes.oneOfType([PropTypes.func, PropTypes.string]),
  addonType: PropTypes.oneOf(['prepend', 'append']).isRequired,
  className: PropTypes.string
};

InputGroupButton.propTypes = {
  tag: PropTypes.oneOfType([PropTypes.func, PropTypes.string]),
  addonType: PropTypes.oneOf(['prepend', 'append']).isRequired,
  children: PropTypes.node,
  groupClassName: PropTypes.string, // only used in shorthand
  groupAttributes: PropTypes.object, // only used in shorthand
  className: PropTypes.string
};

推荐阅读