前言
在使用react+antd开发项目时,有时候需要从SharePoint获取数据,接下来一起了解一下如何使用pnp.js来获取SharePoint中的数据
实现步骤
1、创建项目可以参考【SharePoint Online】01 通过Spfx创建扩展部件(SPFx Application Customizer)
2、安装pnp.js
在vs code终端输入如下命令安装pnp.js
cnpm install sp-pnp-js --save
3、在需要使用的组件中引用pnp
import { sp } from "@pnp/sp";
注意:引用后如果报错property web does not exist on type sprest可以参考【SharePoint】pnp.js报错property web does not exist on type sprest解决方案
完整代码如下
import * as React from "react";
import { Popover, Button, Card, Menu, Dropdown} from 'antd';
import 'antd/dist/antd.css';
import { sp } from "@pnp/sp/presets/all";
export interface IReactFooterProps { }
export interface IReactFooterState {
dataList: Array<{ name: string, url: string }>;
dContent: any;
}
export default class ReactFooter extends React.Component<IReactFooterProps, IReactFooterState> {
constructor(props: IReactFooterProps) {
super(props);
//设置sharepoint请求和环境信息
sp.setup({
sp: {
headers: {
Accept: "application/json;odata=verbose"
},
baseUrl: 'https://sharepoint url'
}
});
this.state = {
dataList: [],
dContent: null
};
}
public handleShowForm = () => {
console.log('11');
}
public componentWillMount() {
let that = this;
sp.web.lists
.getByTitle('DepartmentsList')
.items.get()
.then(async item => {
console.log(item[0].ID);
let dataList = [];
for (let i = 0; i < item.length; i++) {
let list = undefined;
list = { name: item[i].Title, url: item[i].WebUrl };
await dataList.push(list);
console.log('dataList', dataList);
}
await that.setState({
dataList: dataList,
dContent:(
<Menu>
{dataList.length > 0
? dataList.map(item => {
return (
<Menu.Item key={item.url}>{item.name}</Menu.Item>
);
})
: ''}
</Menu>
)
});
});
}
public render(): React.ReactElement<IReactFooterProps> {
return (
<div>
<Dropdown overlay={this.state.dContent}>
<a className="ant-dropdown-link" href="#">
鼠标移入,点击菜单
</a>
</Dropdown>
</div>
);
}
}