【问题标题】:Is there a way to type isActive function of React router NavLink in typescript有没有办法在打字稿中输入 React 路由器 NavLink 的 isActive 函数
【发布时间】:2021-04-14 13:12:44
【问题描述】:
 <MenuItem
          component={NavLink}
          to={to}
          key={text}
          selected={selectedNavIndex === index}
          **// compiler complaining about match of any type**
          isActive={match => {
            if (match) {
              onNavSelectHandler(index);
              return true;
            } else {
              return false;
            }
          }}
        >
          <StyledListItemIcon>
            <StyledIcon as={icon} width={width} />
          </StyledListItemIcon>
          {text && isOpen && <ListItemText primary={text} />}
        </MenuItem>

我正在尝试在打字稿项目中使用react-router的isActive功能,但我无法正确输入...

【问题讨论】:

    标签: reactjs typescript react-router


    【解决方案1】:

    react-router-dom NavLink 组件的 isActive 属性定义如下:

    export interface NavLinkProps<S = H.LocationState> extends LinkProps<S> {
        isActive?<Params extends { [K in keyof Params]?: string }>(match: match<Params> | null, location: H.Location<S>): boolean;
    ...
    

    source link

    您可以导入这个 match 类型(奇怪的是小写)并像这样使用它:

    import {NavLink, match as Match} from "react-router-dom";
    
    <MenuItem
    ...
      isActive={(match: Match | null) => {
        if (match) {
          onNavSelectHandler(index);
          return true;
        } else {
          return false;
        }
      }}
    >
    

    【讨论】:

    • 感谢您的帮助,以及如何输入 isActive 函数的第二个参数(位置)?
    • 从“历史”导入{位置}。通用 描述了位置的状态属性。
    猜你喜欢
    • 1970-01-01
    • 2022-10-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-08
    • 2020-02-02
    • 2021-12-31
    • 2017-07-31
    相关资源
    最近更新 更多