You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

SPFx技术问询:如何使用PnP向SharePoint列表文件夹添加新项?

在SPFx中使用PnPjs向列表文件夹添加项

你可以通过两种简单的方式实现这个需求,下面分别说明具体的代码实现:

方法一:指定父文件夹的服务器相对路径

这种方法需要先获取目标文件夹的ServerRelativeUrl属性,然后在添加列表项时将该路径传入ParentFolderServerRelativeUrl字段:

// 获取目标文件夹并加载其服务器相对路径
sp.web.lists.getByTitle("MyList").rootFolder.folders.getByName("MyFolder")
  .select("ServerRelativeUrl")
  .get()
  .then(folder => {
    // 向列表添加项并指定父文件夹
    return sp.web.lists.getByTitle("MyList").items.add({
      Title: "itemName",
      ParentFolderServerRelativeUrl: folder.ServerRelativeUrl
    });
  })
  .then(result => {
    console.log("项已成功添加到文件夹中", result);
  })
  .catch(error => {
    console.error("添加项失败", error);
  });

方法二:直接通过文件夹的items集合添加

PnPjs的Folder对象提供了items属性,直接指向该文件夹下的列表项集合,你可以直接调用它的add方法来创建新项:

// 直接通过目标文件夹的items集合添加新项
sp.web.lists.getByTitle("MyList").rootFolder.folders.getByName("MyFolder")
  .items.add({
    Title: "itemName"
  })
  .then(result => {
    console.log("项已成功添加到文件夹中", result);
  })
  .catch(error => {
    console.error("添加项失败", error);
  });

注意事项

  • 确保MyFolder确实存在于MyList的根文件夹下,否则会返回文件夹不存在的错误。
  • 如果使用TypeScript开发,你可能需要为自定义字段添加类型定义,避免类型检查报错。

内容的提问来源于stack exchange,提问作者Alessandra Amosso

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.06 16:12:47