React第三课笔记-简单使用ANTD(Ant Design)
以抽屉为例,在 create-react-app 中使用,以下是实现的步骤
1. 安装antd
2. 引入css样式
3. 引入组件
4. 复制代码
5. 根据需求更改代码
第一步:安装antd
npm i antd -- save
第二步:引入想要使用组建的css样式,修改src/App.css文件,在最前面加上
@import '~antd/dist/antd.css';
第三步:引入组件
import { Drawer } from 'antd'
第四步:复制代码,这里我只复制了Drawer基本样式中代码的一部分,全部代码在抽屉 Drawer中
<Drawer
title="Basic Drawer"
placement="right"
closable={false}
onClose={this.onClose}
visible={this.state.visible}
>
<p>Some contents...</p>
<p>Some contents...</p>
<p>Some contents...</p>
</Drawer>
第五步:将复制的代码整合到App.js中
import React, { Component } from 'react';
import './App.css';
import { Drawer } from 'antd'
class App extends Component {
constructor() {
super()
this.state = {
visible: false
}
}
onClose = ()=>{
this.setState({
visible :false
})
}
//箭头函数 this保留作用域
render() {
return (
<div className="App">
<button
onClick = {()=>{this.setState({
visible : true
})}}
>
抽屉
</button>
<Drawer
title="Basic Drawer"
placement="right"
closable={false}
onClose={this.onClose}
visible={this.state.visible}
>
<p>Some contents...</p>
<p>Some contents...</p>
<p>Some contents...</p>
</Drawer>
</div>
);
}
}
export default App;
最后
npm start
运行就好啦
问题:
1. 为什么onClose函数放在构造函数constructor里面会报错
Line 15: ‘onClose’ is not defined no-undef
2.箭头函数保留作用域问题:
没箭头函数时调用 :onClose : {()=>{this.onClose()}
有箭头函数时调用:onClose : {this.onClose}
3.JSX只能有一个根节点