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

如何在SharePoint中使用SPFx显示当前登录用户的名字

解决SPFx Web部件仅显示登录用户名字的问题

你当前的代码会遍历所有用户属性并拼接展示,要只显示用户名字,只需要定位到对应的用户属性项即可,以下是修改后的代码及说明:

private GetUserProperties(): void {
  pnp.sp.profiles.myProperties.get().then((result) => {
    // 查找用户属性中Key为"FirstName"的项(对应名)
    const firstNameProp = result.UserProfileProperties.find(property => property.Key === "FirstName");
    // 如果需要显示完整用户名(如"张三"),可替换为Key="PreferredName"
    // const fullNameProp = result.UserProfileProperties.find(property => property.Key === "PreferredName");

    // 设置默认值,避免找不到属性时显示空白
    let userName = "访客";
    if (firstNameProp) {
      userName = firstNameProp.Value;
    }

    // 确保DOM元素存在后再赋值,避免报错
    const targetElement = document.getElementById("FirstName");
    if (targetElement) {
      targetElement.innerHTML = `欢迎你,${userName}!`;
    }
  })
  .catch((error) => { console.log("获取用户属性出错: " + error); });
}

关键修改点:

  • 使用find方法替代forEach,直接筛选出目标属性项,无需遍历所有属性
  • 添加默认值,防止用户属性不存在时页面显示空白
  • 增加DOM元素存在性检查,避免因元素未加载导致的空指针错误
  • 改用箭头函数,更符合现代JavaScript写法,同时避免this指向问题

如果需要展示用户的完整显示名(而非仅名字),只需要将find方法中的Key值替换为"PreferredName"即可,这个属性通常存储用户的全名。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 09:35:24