0

我是 Fluent UI React 组件的新手。我正在尝试从流畅的 UI 反应在命令栏控件上实现 React Router,在这里发现它是带有溢出菜单项的 CommandBar。如果我想使用菜单项导航到不同的页面,我会使用 history.push("/myLink") ,如此所述。但是为了使该工作正常进行,我需要访问功能组件中的 useState 。代码如下所示:

        export const CommandBarBasicExample: React.FunctionComponent = () => {
        const [refreshPage, setRefreshPage] = useState(false);
      return (
        <div>
          <CommandBar
            items={_items}
            overflowItems={_overflowItems}
            overflowButtonProps={overflowProps}
            farItems={_farItems}
            ariaLabel="Use left and right arrow keys to navigate between commands"
          />
        </div>
      );
    };

    const _items: ICommandBarItemProps[] = [
      {
        key: 'newItem',
        text: 'New',
        cacheKey: 'myCacheKey', // changing this key will invalidate this item's cache
        iconProps: { iconName: 'Add' },
        subMenuProps: {
          items: [
            {  //first item in the menu
        key: "AddProperty",
        text: "Properties",
        iconProps: { iconName: "Add" },
        ["data-automation-id"]: "newProperty", // optional
        onClick: ()=>{handleclick()
        setRefreshPage(true);
        };
            {
              key: 'calendarEvent',
              text: 'Calendar event',
              iconProps: { iconName: 'Calendar' },
            },
          ],
        },
      },

我遇到的问题是,如果我使用 setRefreshPage(true) VS 代码抱怨状态变量无法识别。如果我将 useState 放在其他地方,则对非法使用 useState 的投诉做出反应。如何让 useState 在 const _items 对象中可用?任何帮助将不胜感激。

4

1 回答 1

1

这是使用相同命令栏组件对我有用的方法。

您必须确保您的路由器设置为HashRouter,并且您的路径属性<Route/>设置为/#properties通过href按钮的属性 - 而不是通过onClick.

我们有描述路线的路线文件:

/* routes.js */
export const Routes = {
   Properties: 'properties'
}

我们有这个文件,描述命令栏的内容。

/* commandBarItems.js */

import Routes from './routes'
// IMPORTANT - CHECK OUT THE HREF PROP
const PropertiesButton = { key: Routes.Properties, name: 'Properties', href: `#${Routes.Properties}` };

export const CommandBarItems = { menu: [PropertiesButton] }

我们有app.js你设置哈希路由器和命令栏组件的地方。

/* app.js */
import React, { Component } from 'react';
import { HashRouter as Router, Route } from "react-router-dom";
import { Fabric, initializeIcons, CommandBar } from 'office-ui-fabric-react';
import { PropertiesComponent } from './whichever-file-or-module';
import Routes from './routes';
import CommandBarItems from './commandBarItems';

class App extends Component {
    constructor() {
        super();
        initializeIcons();
        ...
    }

    render() {
        return (
          <div>
            <Fabric>
              <Router>
                <React.Fragment>
                  <CommandBar items={CommandBarItems.menu} farItems={CommandBarItems.farItems}/>
                  <Route path={`/${Routes.Properties}`} component={PropertiesComponent} />
                </React.Fragment>
              </Router>
             </Fabric>
            </div>
          );
     }
}
于 2020-11-12T00:22:45.393 回答