SharePoint Framework(也称为 SPFx)Web 部件,使用 React 和 REST API






3.40/5 (5投票s)
SharePoint Framework WebPart,用于使用 React 和 REST API 检索列表项。
引言
SharePoint Framework (SPFx) 完全支持客户端 SharePoint 开发。这提供了与 SharePoint 数据轻松集成。它与现代技术和工具兼容。您可以使用自己的 IDE,无需购买 Visual Studio。此外,SPFx 在设计上是响应式的。
本文讨论了使用 SharePoint Framework Web 部件与 React 作为框架。整篇文章将引导您完成从先决条件、理解 SPFx Web 部件、配置、构建和部署的整个生命周期。
Using the Code
代码使用 React 在 SharePoint 页面上进行渲染。REST API 从 SharePoint 列表中获取数据。
数据源会在特定时间间隔刷新。只有当数据值与当前 DOM 相比发生变化时,页面才会更新。无需刷新页面即可查看更新的数据。状态一改变,React 就会自动更新 DOM。
先决条件
以下是从安装和学习角度来看的先决条件。下方提供了安装链接的参考。您还需要创建一个 SharePoint 开发人员和应用目录站点,这些在部署代码时会非常有用。
别忘了创建如下所示的包含列的 SharePoint 列表。
安装
- Node.js 和 npm:https://node.org.cn/en/download
- Yeoman 和 Gulp:以管理员身份打开命令提示符。使用以下命令安装 gulp 和 yeoman。
npm install -g yo gulp
- Visual Studio Code:https://vscode.js.cn/docs/setup/windows
创建应用目录和开发站点
- 应用目录:转到 SharePoint 管理中心。然后转到应用,您将看到创建一个应用目录站点的选项。
- 开发站点:转到https://yourtenannt.sharepoint.com/_layouts/15/online/SiteCollections.aspx
创建 SharePoint 列表
使用以下文本类型的列创建 SharePoint 列表。
创建 SPFx Web 部件
完成所有必需组件的安装后,就可以创建 SPFx Web 部件了。运行以下命令并选择屏幕下方显示的选项。此命令将启动 yeoman 开始创建 SharePoint Web 部件。
yo @microsoft/sharepoint
创建 Web 部件需要一段时间。
安装 Jquery
npm install --save jquery
npm install --save @types/jquery
理解 SPFx Web 部件文件结构
在命令提示符中,使用 code .
在 VSCode 中打开新创建的解决方案。整个解决方案中有许多文件,以下是本文将重点讨论的重要文件。
完整性检查
让我们检查解决方案是否可以通过 gulp 构建。
在命令提示符窗口中运行以下命令。请确保您位于创建 Web 部件的目录中。
gulp build
解决方案已构建,让我们开始理解和更新解决方案中的文件。
ReactGetItems.module.scss
这类似于 SPFx Web 部件的 CSS 文件。用以下代码覆盖您的文件。
.tableStyle{
display: table ;
margin-left : 50px ;
}
.panelStyle{
background: white ;
}
.divStyle{
background: #eee ;
padding: 20px ;
margin: 20px ;
}
.headerCaptionStyle{
background: white ;
display: table-row ;
border: solid ;
text-align : center ;
width : 420px ;
height : 30px ;
padding-top : 3px ;
color : white ;
margin-left : 100px ;
display : block ;
}
.headerStyle{
background: #4B6978 ;
display: table-row ;
border: solid ;
text-align : center ;
width : 100px ;
height : 30px ;
padding-top : 10px ;
color : white ;
}
.tableCaptionStyle{
background:#4B6978 ;
display: block ;
font-size : 20px ;
font-weight: bold ;
border: solid ;
text-align : center ;
width : 650px ;
height : 30px ;
padding-top : 3px ;
border-radius: 25px ;
margin-left : 30px ;
margin-top : 20px ;
color:white;
}
.rowCaptionStyle{
width : 600px ;
display : table-caption ;
background: #4B6978 ;
text-align : center ;
padding: 20px ;
font-size : 20px ;
font-weight : bold ;
color : white ;
}
.rowStyle{
display : table-row ;
background: #eee ;
padding: 20px ;
margin: 20px ;
font-weight : bold ;
}
.CellStyle{
display: table-cell ;
border: solid ;
border-color : white ;
text-align : center ;
width : 100px ;
height : 30px ;
padding-top : 10px ;
}
IReactSpfxWebPartProps.ts
让我们更新我们的 IReactSpfxWebPartProps.ts。这是我们的 React 接口。
Siteurl
属性用于将站点上下文传递给 Web 部件。Description 是您 Web 部件的描述。
export interface IReactSpfxWebPartProps {
description: string;
siteurl: string;
}
ReactSpFxWebPart.tsx
这是由于我们选择了 React 框架而生成的最重要的文件。用以下代码覆盖您解决方案中的文件。
IReactSpfxState
:状态接口ReactGetItems
:类文件constructor
:初始化状态componentDidMount
:React 组件fetchDatafromSharePointList
:此方法使用 REST API 获取数据render
:渲染 HTML
import * as React from 'react';
import styles from './ReactSpfxWebPart.module.scss';
import { IReactSpfxWebPartProps } from './IReactSpfxWebPartProps';
import * as jquery from 'jquery';
export interface IReactSpfxState{
items:[
{
"Courses": "",
"Credit": "",
"Department":"",
}]
}
export default class ReactGetItems
extends React.Component<IReactSpfxWebPartProps, IReactSpfxState> {
public constructor(props: IReactSpfxWebPartProps, state: IReactSpfxState){
super(props);
this.state = {
items: [
{
"Courses": "",
"Credit": "",
"Department":"",
}
]
};
}
private componentDidMount() {
setInterval(
() => this.fetchDatafromSharePointList(),
1000
);
}
private fetchDatafromSharePointList()
{
var reactHandler = this;
jquery.ajax({
url: `${this.props.siteurl}/_api/web/lists/getbytitle('CourseDetails')/items`,
type: "GET",
headers:{'Accept': 'application/json; odata=verbose;'},
success: function(resultData) {
/*resultData.d.results;*/
reactHandler.setState({
items: resultData.d.results
});
},
error : function(jqXHR, textStatus, errorThrown) {
}
});
}
public render(): React.ReactElement<IReactSpfxWebPartProps> {
return (
<div className={styles.panelStyle} >
<div className={styles.tableCaptionStyle} >Fetch
Course Details from SharePointList using SPFx,RESTAPI,React JS
Data on page changes with change in the SharePointList </div>
<div className={styles.headerCaptionStyle} >Course Details</div>
<div className={styles.tableStyle} >
<div className={styles.headerStyle} >
<div className={styles.CellStyle}>Courses</div>
<div className={styles.CellStyle}>Credit </div>
<div className={styles.CellStyle}>Department</div>
</div>
{this.state.items.map(function(item,key){
return (<div className={styles.rowStyle} key={key}>
<div className={styles.CellStyle}>{item.Courses}</div>
<div className={styles.CellStyle}>{item.Credit}</div>
<div className={styles.CellStyle}>{item.Department}</div>
</div>);
})}
</div>
</div>
);
}
}
ReactSpfxWebPartWebPart.ts
这是 SPFx 创建的主文件。它与 Component 文件夹下的 React 文件进行交互。最终渲染在这里发生。
import * as React from 'react';
import * as ReactDom from 'react-dom';
import { Version } from '@microsoft/sp-core-library';
import {
BaseClientSideWebPart,
IPropertyPaneConfiguration,
PropertyPaneTextField
} from '@microsoft/sp-webpart-base';
import * as strings from 'reactSpfxWebPartStrings';
import ReactSpfxWebPart from './components/ReactSpfxWebPart';
import { IReactSpfxWebPartProps } from './components/IReactSpfxWebPartProps';
import { IReactSpfxWebPartWebPartProps } from './IReactSpfxWebPartWebPartProps';
export default class ReactSpfxWebPartWebPart
extends BaseClientSideWebPart<IReactSpfxWebPartWebPartProps> {
public render(): void {
const element: React.ReactElement<IReactSpfxWebPartProps > = React.createElement(
ReactSpfxWebPart,
{
description: this.properties.description,
siteurl: this.context.pageContext.web.absoluteUrl
}
);
ReactDom.render(element, this.domElement);
}
protected get dataVersion(): Version {
return Version.parse('1.0');
}
protected getPropertyPaneConfiguration(): IPropertyPaneConfiguration {
return {
pages: [
{
header: {
description: strings.PropertyPaneDescription
},
groups: [
{
groupName: strings.BasicGroupName,
groupFields: [
PropertyPaneTextField('description', {
label: strings.DescriptionFieldLabel
})
]
}
]
}
]
};
}
}
IReactSpfxWebPartWebPartProps.ts
WebPart
属性的接口。
export interface IReactSpfxWebPartWebPartProps {
description: string;
}
配置
copy-assets.json
要复制到 SharePoint 资源库的文件夹位置。
{
"deployCdnPath": "temp/deploy"
}
write-manifests.json
temp/deploy 下创建的所有文件都应复制到此处,以便 React Web 部件可以在 SharePoint 中运行。
{
"cdnBasePath": "https://yourtenant/sites/intranet/Site%20Assets"
}
package-solution.json
大多数字段都很有用。最重要的字段是 zippedpackage
。这是创建包的位置。
{
"solution": {
"name": "react-spfx-web-part-client-side-solution",
"id": "7d2fa690-094d-4445-b012-97d462b335ae",
"version": "1.0.0.0",
"skipFeatureDeployment": true
},
"paths": {
"zippedPackage": "solution/react-spfx-web-part.sppkg"
}
}
ReactSpfxWebPartWebPart.manifest.json
{
"$schema": "../../../node_modules/@microsoft/sp-module-interfaces/lib/
manifestSchemas/jsonSchemas/clientSideComponentManifestSchema.json",
"id": "3a5f40ec-b0c9-4a4f-acc1-24be14e318f2",
"alias": "ReactSpfxWebPartWebPart",
"componentType": "WebPart",
// The "*" signifies that the version should be taken from the package.json
"version": "*",
"manifestVersion": 2,
// If true, the component can only be installed
// on sites where Custom Script is allowed.
// Components that allow authors to embed arbitrary
// script code should set this to true.
// https://support.office.com/en-us/article/
// Turn-scripting-capabilities-on-or-off-1f2c515f-5d7e-448a-9fd7-835da935584f
"requiresCustomScript": false,
"preconfiguredEntries": [{
"groupId": "3a5f40ec-b0c9-4a4f-acc1-24be14e318f2",
"group": { "default": "Under Development" },
"title": { "default": "ReactSpfxWebPart" },
"description": { "default": "Retrieving list
items and auto refresh on change of data on SharePoint List" },
"officeFabricIconFontName": "Page",
"properties": {
"description": "ReactSpfxWebPart"
}
}]
}
构建您的项目
我们将使用 gulp 来构建项目。运行以下命令开始构建项目。项目成功构建后,您将在 temp/deploy 文件夹下看到一些文件。这些文件包含捆绑的 JavaScript 和元数据文件,对于 Web 部件在 SharePoint 中的运行至关重要。
这会在 temp/deploy 下创建文件,需要将这些文件复制到您站点的 Assets 文件夹。
gulp build
gulp -ship
运行以下命令将在目标路径中创建 sppkg
文件。
gulp bundle --ship
gulp package-solution --ship
文件夹结构
下图可以帮助您找到部署到 SharePoint 所需的文件。
SharePoint 和本地工作台
在命令提示符中输入以下命令。此命令启动 gulp
并在浏览器中打开本地工作台。
gulp serve
这有助于在将包部署到 SharePoint 之前测试 Web 部件。Web 部件可以在本地工作台以及 SharePoint 工作台上进行测试。
在 SharePoint 工作台上进行测试将从 SharePoint 列表中检索数据。
本地工作台
在本地工作台上进行测试仅在创建了模拟数据的情况下才能检索数据。
部署
现在是将包文件部署到 SharePoint 应用目录站点的时候了。
Web 部件已部署到 SharePoint
将 Web 部件添加到 AppCatalog
后,它就可以添加到 SharePoint 开发人员或任何其他网站集了。
参考文献
- https://dev.office.com/sharepoint/docs/spfx/sharepoint-framework-overview
- https://fbdocs.cn/react
- https://yeoman.node.org.cn
- https://gulp.node.org.cn
历史
- 2017年9月21日:初始版本