版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/shrenk/article/details/85064193
首先创建spfx webpart项目:
使用VS Code打开,然后在terminal中安裝pnpjs包:
安装完成之后,在webpart代码文件(这里是CreatePageWebPart.ts)中,从pnpjs包中导入需要用到的对象如下:
然后修改render方法,添加一个按钮,点击按钮的时候执行addPage方法,定义如下:
具体代码以及注释如下,不要忘记导入react和react-dom。
import * as React from 'react';
import * as ReactDom from 'react-dom';
... ...
public render(): void {
//render一个按钮,绑定onClick事件
ReactDom.render(
React.createElement('button',
{
onClick:this.addPage.bind(this)
},
'Add Page'),
this.domElement
)
}
private addPage(){
//使用addClientSidePage方法添加一个页面,指定页面name和title
//默认会将页面添加到Site Pages文档库中
sp.web.addClientSidePage('newpage.aspx', 'New Page').then((page) =>{
//为页面添加一个section
const section = page.addSection();
//向section中添加html代码
section.addControl(new ClientSideText('<h1>this is a new page</h1>'));
//保存页面
page.save();
}).catch(err=>{console.log(err);});
}
运行gulp serve, 因为要访问SharePoint,所以打开online的工作台,添加webpart,显示“Add Page”按钮,点击之后,会自动在Site Pages文档库里添加一个页面:
除了创建页面和在页面上添加html代码之外,还可以使用addControl方法添加webpart。可以使用下面的方法,列出所有OOTB以及安裝的自定义的client webpart:
sp.web.getClientSideWebParts().then(
wp=>console.log(wp)
);
作为演示,我们添加一个News Link webpart。修改代码,添加一个editPage函数,然后将“Add Page”按钮改为“Edit Page”,并将editPage方法绑定到onClick事件上,代码和注释如下:
public render(): void {
//修改按钮属性
ReactDom.render(
React.createElement('button',
{
onClick:this.editPage.bind(this)
},
'edit Page'),
this.domElement
)
}
private editPage(){
//这里列出所有webpart的信息,可以找到需要添加的webpart的id
sp.web.getClientSideWebParts().then(wp=>console.log(wp));
//获取刚刚新建的页面
const pageFile = sp.web.getFileByServerRelativeUrl(`${this.context.pageContext.web.serverRelativeUrl}/SitePages/newpage.aspx`);
ClientSidePage.fromFile(pageFile).then((page) =>{
//添加一个新section
const section = page.addSection();
//创建一个New Link webpart
const webpart = new ClientSideWebpart('New Link', null, {}, 'c1b5736d-84dd-4fdb-a7be-e7e9037bd3c3');
//将webpart添加到section中
section.addControl(webpart);
//保存页面
page.save();
}).catch(err=>{console.log(err);});
}
重新运行gulp serve,点击“Edit Page”按钮,打开创建的页面可以看到News Link webpart。
除此之外,pnpjs还提供了其他针对页面的操作,例如查找页面上的control,添加comments等,具体使用方法请参考:https://pnp.github.io/pnpjs/sp/docs/client-side-pages/