打字稿:如何从 react-bootstrap 导入特定组件 [英] Typescript: How to import specific component from react-bootstrap

查看:30
本文介绍了打字稿:如何从 react-bootstrap 导入特定组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

之前我的应用程序是在 ReactJs + React-bootstrap 中.现在我正在使用 Typescript + ReactJs + React-bootstrap

Earlier my app was in ReactJs + React-bootstrap. Now I'm using Typescript + ReactJs + React-bootstrap

为了减少生产应用程序的大小之前我曾经使用 - 导入 react-bootstrap 组件从'react-bootstrap/lib/Button'导入按钮

To reduce the size of the app for production Earlier I used to import react-bootstrap components using - import Button from 'react-bootstrap/lib/Button'

添加 Typescript 后显示以下错误

After adding Typescript it shows the following error

错误在 [at-loader] ./components/Hello.tsx:6:8TS1192:模块react-bootstrap/lib/Button"没有默认导出.

ERROR in [at-loader] ./components/Hello.tsx:6:8 TS1192: Module ''react-bootstrap/lib/Button'' has no default export.

试用版 1

import {Button} from 'react-bootstrap/lib/Button' 但在这种情况下 Button 未定义.

import {Button} from 'react-bootstrap/lib/Button' but in this case Button is undefined.

试用 2

import * as Button from 'react-bootstrap/lib/Button' 但在这种情况下会弹出另一个错误

import * as Button from 'react-bootstrap/lib/Button' but in this case another error pops out

错误在 [at-loader] ./components/Hello.tsx:54:12TS2604:JSX 元素类型Button"没有任何构造或调用签名.

ERROR in [at-loader] ./components/Hello.tsx:54:12 TS2604: JSX element type 'Button' does not have any construct or call signatures.

此错误在行 <Button onClick={handleClick} bsStyle="danger" bsClass="glyphicon glyphicon-new-window"></Button>

虽然 import {Button} from 'react-bootstrap' 工作正常,但这不是我们想要的,因为它会导致应用程序的大小增加 200kbs.

Though import {Button} from 'react-bootstrap' works fine but this is not desired because it results in increasing the size of the app by 200kbs for me.

我们如何使用 Typescript 从 react-bootstrap 导入特定组件??

How can we import specific component from react-bootstrap using Typescript??

推荐答案

由于 TypeScript 遵循 ESModule 规范,但 lib 使用的是 CommonJS,因此您必须使用 React切换到 TypeScript 时导入.

Since TypeScript adheres to the ESModule spec but the lib is using CommonJS, you have to to the sam, you did with the React import when you switched to TypeScript.

JS

import React from 'react'
import Button from 'react-bootstrap/lib/Button'

打字稿

import * as React from 'react'
import * as Button from 'react-bootstrap/lib/Button'

无耻的自插:我写了这个的原因这里.我想你以后会再次遇到这个问题:)

Shameless self plug: I wrote about the reason for this here. I guess you will run into this issue in the future again :)

这是我使用的版本:

{
  "@types/react-bootstrap": "^0.0.47",
  "react-bootstrap": "^0.30.8"
}

这篇关于打字稿:如何从 react-bootstrap 导入特定组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆