当链接 属性 中有链接 属性 时如何设置 Nav 组件的 selectedKey 属性 - Fabric React Nav

How to set the selectedKey property of a Nav component when there is a links property within a links property - Fabric React Nav

我刚刚开始学习 React 并遵循了一些入门教程,所以请原谅我的问题很愚蠢或者使用的代码总体上很糟糕(请不要犹豫让我知道),但是在谷歌搜索之后我似乎找不到以下问题的答案:

我正在使用带有 JS 实现(而不是 TS)的 Fabric React。我使用我在此处找到的示例成功集成了我的 Nav 组件:https://developer.microsoft.com/en-us/fabric#/components/nav

遗憾的是,这个例子错过了 selected 事件的实现(用蓝色条突出显示所选项目),该示例只是将 Nav 组件的所选项目硬编码为键:键 1:

selectedKey={'key1'}

经过一些研究,我发现了添加一个更改选择的选定事件的完美示例,我在这里找到了它:https://codepen.io/dzearing/pen/ZBGNQg?editors=0010

我重写了它以便可以在我的 JS 文件中使用它:

let navGroups = [
  {
    links: [
      {
        name: 'Home', 
        url: '#', 
        key: '#', 
        icon: 'HomeSolid', 
      },
      {
        key: '#recent',
        name: 'Recent',
        url: '#recent'
      },
      {
        key: '#photos',
        name: 'Photos',
        url: '#photos'
      },
      {
        name: 'Settings',
        url: '#',
        key: '#next', 
        links: [
          {
            name: 'Staff',
            url: '#',
            key: '#key2',
            icon: 'People'
          },
          {
            name: 'Restrictions',
            url: '#',
            key: '#key3',
            icon: 'Lock'
          }
        ],
        isExpanded: true,
        icon: 'Settings',
      },
    ]
  }
];

class NavBar extends React.Component {
  constructor(props) {
    super(props);
    this._onClickHandler = this._onClickHandler.bind(this);
    this.state = {
      selectedNavKey: '#'
    }
  }

  render() {
    let { selectedNavKey } = this.state;

    return (
      <div className="ms-Nav-LeftPane">
        <Nav
          selectedKey={ selectedNavKey }
          groups={ navGroups }
        />
      </div>
    );
  }

  componentDidMount() {
    window.addEventListener('hashchange', () => {
      this.setState({ selectedNavKey: document.location.hash || '#' });
    })
  }

}

所选事件对常规按钮工作正常,但由于某些原因它不适用于 Settings 导航项目,它有自己的 Links 项目。知道为什么这对 Settings 项不起作用吗?

我找到了解决方案。

问题是我在 selectedNavKey 状态使用的 URL 属性 上有相同的值:

 componentDidMount() {
    window.addEventListener('hashchange', () => {
      this.setState({ selectedNavKey: document.location.hash || '#' });
    })
  } 

Settings navitem,它是child的,都在他们的url 属性中使用了#,这导致了selectedNavKey: document.location.hash || '#' 无法正常工作。我从来不知道 document.location.hash 函数使用 url 但在阅读以下内容后它变得更加清晰:

Hash-Based & Push-State URLs In React