呈现ui构造react nav组件时防止页面重新加载

时间:2018-08-29 08:30:08

标签: reactjs typescript office-ui-fabric

我一直想让ui-fabric Nav组件与react-router-dom v4 +一起使用。我的解决方案“有效”,但是整个页面被重新渲染,而不仅仅是NavSelection组件。经过一番研究,我意识到我需要在某个地方做一个e.preventDefault(),但是我不知道该在哪里添加它。

主页:

$(document).ready(function() {

$('body').scroll(function() {
 var scroll = $('body').scrollTop();
 if (scroll <= 50 ) {
     console.log(scroll);
   we
    } else {
    $("#label").css('fill', 'none');
    $(".label").addClass(".transition");
 }
 if (scroll <= 150) {
    $(".sizeLG").css('color', '#ffffff');
 } else {
    $(".sizeLG").css('color', '#00000000');
    $(".sizeLG").addClass(".transition");
 }
});

导航栏:

    export const Home = () => {
        return (
            <div className="ms-Grid-row">
                <div className="ms-Grid-col ms-u-sm6 ms-u-md4 ms-u-lg2">
                    <Navbar />
                </div>
                <div className="ms-Grid-col ms-u-sm6 ms-u-md8 ms-u-lg10">
                    <NavSelection />
                </div>
            </div>
        );
    }

NavSelection:

const navGroups = [
  {
    links: [
      { name: 'Name1', url: '/Name1', key: '#Name1' },
      { name: 'Name2', url: '/Name2', key: '#Name2' }
    ]
  }
];

export class Navbar extends React.Component<any, any> {
  constructor(props: INavProps) {
    super(props);

    this.state = {
      selectedNavKey: '#Name1'
    };
  }

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

  public render(): JSX.Element {
    const { selectedNavKey } = this.state;

    return (
      <Nav
        selectedKey={selectedNavKey}
        groups={navGroups}
      />
    );
  }
}

非常感谢您的帮助

编辑:我试图像这样将其放入componentDidMount中:

export const NavSelection = () => {
    return (
        <div>
            <Route path="/Name1" component={Component1} />
            <Route path="/Name2" component={Component2} />
        </div>
    );
}

那行不通。

3 个答案:

答案 0 :(得分:1)

我猜您正在使用Microsoft的https://developer.microsoft.com/en-us/fabric#/components/nav#Variants

在这种情况下,您需要在导航项上指定回调。通常在反应中使用window.addEventListener之类的方法是反模式。

这看起来像。

export class Navbar extends React.Component<any, any> {
  constructor(props: INavProps) {
    super(props);

    this.state = {
      selectedNavKey: '#Name1'
    };
  }

  public handleNavClick(event, { key, url }) {
      // You also need to manually update the router something like
      history.push(url);
      this.setState({ selectedNavKey: key });
  }

  public render(): JSX.Element {
    const { selectedNavKey } = this.state;

    return (
      <Nav
        selectedKey={selectedNavKey}
        groups={{
          links: [
            { name: 'Name1', url: '/Name1', key: '#Name1', onClick: this.handleNavClick },
            { name: 'Name2', url: '/Name2', key: '#Name2', onClick: this.handleNavClick }
          ]
        }}
      />
    );
  }
}

答案 1 :(得分:1)

使用 HashRouter 代替 BrowserRouter

示例:

路由器:

...

import { Switch, Route, Redirect, HashRouter } from 'react-router-dom'

...

export const Router: React.FunctionComponent = () => {

  // persisted to localStorage
  const navActiveItem = useSelector(selectNavActiveItem)

  return (
    <Suspense fallback={<LargeSpinner />}>
      <HashRouter>
        <Switch>
          <Route exact path="/" render={() => (
            <Redirect to={navActiveItem.url} />
          )}/>

          <Route exact path="/dashboard/overview" component={Overview} />
          <Route exact path="/dashboard/progress" component={Progress} />
          <Route exact path="/dashboard/issues" component={Issues} />

          ...

        </Switch>
      </HashRouter>
    </Suspense>
  )
}

导航:

...

const navLinkGroups: INavLinkGroup[] = [
  {
    name: 'Dashboard',
    expandAriaLabel: 'Expand Dashboard section',
    collapseAriaLabel: 'Collapse Dashboard section',
    links: [
      {
        key: 'DashboardOverview',
        name: 'Overview',
        icon: 'BIDashboard',
        url: '#/dashboard/overview',
      },
      {
        key: 'DashboardProgress',
        name: 'Progress',
        icon: 'TimelineProgress',
        url: '#/dashboard/progress',
      },
      {
        key: 'DashboardIssues',
        name: 'Issues',
        icon: 'ShieldAlert',
        url: '#/dashboard/issues',
      },
    ],
  },
...

export const Navigation: React.FunctionComponent = () => {
  const navActiveItem = useSelector(selectNavActiveItem)
  const dispatch = useDispatch()

  const onLinkClick = (ev?: React.MouseEvent<HTMLElement>, item?: INavLink) => {
    dispatch(setNavActiveItem(item || { name: '', url: '/' }))
  }

  return (
    <Stack tokens={stackTokens} styles={stackStyles}>
      <Nav
        styles={navStyles}
        ariaLabel="Navigation"
        groups={navLinkGroups}
        onLinkClick={onLinkClick}
        initialSelectedKey={navActiveItem.key}
      />
    </Stack>
  )
}

答案 2 :(得分:0)

为防止页面刷新,请在Nav组件的onLinkClick事件处理程序中调用event.preventDefault():

<Nav onLinkClick={linkClickHandler} selectedKey={selectedKey} />

function linkClickHandler(event,{key, url}){
     event.preventDefault();
     setSelectedKey(key);

     console.log(url);
}