本文主要是介绍使用SPFx和pnpjs添加并且定制化页面,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
首先创建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) =>{//为页面添加一个sectionconst 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的idsp.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) =>{//添加一个新sectionconst section = page.addSection();//创建一个New Link webpartconst 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/
这篇关于使用SPFx和pnpjs添加并且定制化页面的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!