React 中高阶无状态组件的 props 的 Typescript 问题

Typescript issues with props of higher order stateless component in React

我正在尝试按照 react-router 教程创建 NavLink。但我不明白为什么以下内容不适用于 Typescript 2.1

import React from 'react';
import { Link, LinkProps } from 'react-router';

const NavLink: React.SFC<LinkProps> = (props) => (
  <Link {...props} activeClassName="active" />
);

我不断得到:

file: 'file:///Users/bjarkehs/Code/lytzentid-reloaded-frontend/src/components/shared/NavLink.tsx'
severity: 'Error'
message: 'Property 'ref' of JSX spread attribute is not assignable to target property.
  Type 'Ref<Link>' is not assignable to type 'string | (string & ((instance: Link) => any)) | (((instance: Component<LinkProps, ComponentState>...'.
    Type '(instance: Link) => any' is not assignable to type 'string | (string & ((instance: Link) => any)) | (((instance: Component<LinkProps, ComponentState>...'.
      Type '(instance: Link) => any' is not assignable to type '((instance: Component<LinkProps, ComponentState>) => any) & ((instance: Link) => any)'.
        Type '(instance: Link) => any' is not assignable to type '(instance: Component<LinkProps, ComponentState>) => any'.'
at: '5,9'
source: 'ts'

我认为这是一个 react-router 类型问题。在您使用的类型中,您可能有一行代码如下所示:

interface LinkProps extends React.HTMLAttributes<Link>, React.Props<Link> {

使用当前的 React 类型,props 接口不应再扩展 React.Props。所以该行应该改为:

interface LinkProps extends React.HTMLAttributes<Link> {

我根据您发布的代码测试了此更改,它为我修复了错误。

我也遇到过这个问题。但是,与其从第三方组件更改类型,我觉得最好通过为该变量禁用 Typescript,通过将 props 分配给另一个变量并强制转换为 any 来从我们的最终更改它,如下所示:

const NavLink: React.SFC<LinkProps> = (props) => (
  const linkProps: any = props;
  <Link {...linkProps} activeClassName="active" />
);