使用Create-React-App和antd

5

我尝试在创建的React应用程序中使用antd

我通过以下方式在项目中安装了antd。

yarn add antd

使用antd的按钮组件添加了一个按钮

import React, { Component } from 'react';
import Button from 'antd/lib/button';
import './App.css';

class App extends Component {
  render() {
    return (
      <div className="App">
        <Button type="primary">Button</Button>
      </div>
    );
  }
}

export default App;

不过,按钮仍未正确呈现。检查元素时,我发现应用了 antd 类。只是 css 没有加载。

4个回答

4

我需要在src/App.css的顶部添加antd/dist/antd.css。

@import '~antd/dist/antd.css';

.App {
  text-align: center;
}

我从antd官方文档中,关于创建React App使用的说明中了解到以下步骤:
只需安装antd即可。
yarn add antd

使用 antd 组件
import React, { Component } from 'react';
import Button from 'antd/lib/button';
import './App.css';

class App extends Component {
  render() {
    return (
      <div className="App">
        <Button type="primary">Button</Button>
      </div>
    );
  }
}

export default App;

在主CSS文件(src/App.css)中导入antdcss。

1
尽管验证的答案可行,但您可以通过仅导入所需的CSS来最小化构建中CSS包的大小。
import Button from 'antd/lib/button';
import 'antd/lib/button/style/css'; // importing only the required CSS

更新

最近注意到即使按照上述方式导入antd组件,它仍然会在构建中添加不必要的JS。

我甚至尝试使用react-app-rewired在ant design文档中解决问题,但结果还是一样(仍然会在构建中添加不必要的JS)。因此,我在antd repo上打开了一个问题:https://github.com/ant-design/ant-design/issues/13274

更新2:

请看:https://github.com/ant-design/ant-design/issues/12011


这仍然会导入许多不必要的样式,因为 'antd/lib/button/style/css' 导入了基础 CSS。 - Kevin He
@KevinHe 你有更好的解决方案吗?如果有,请继续编辑回答。 - user158

0
在你的项目中安装了 antd 之后,你可以这样导入 button:
```javascript import { Button } from 'antd'; ```

0

首先通过npm安装less-loader,命令为npm i less-loader, 然后在index.js目录下创建一个index.less文件夹。 将以下代码粘贴到index.less中 -> @import "~antd/dist/antd.dark.less"; 之后将这个.less文件导入到你的index.js中,尽情享受吧 :) 你可以在这里找到其他方法。

你也可以使用craco(create react app config override),但它更加复杂。


1
你的答案可以通过提供额外的支持信息来改进。请[编辑]以添加更多细节,比如引用或文档,这样其他人就能确认你的答案是否正确。你可以在帮助中心找到更多撰写好答案的信息。 - Community

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接