Reactjs 如何在不更改React.Component的所有用法的情况下扩展React组件属性类型

Reactjs 如何在不更改React.Component的所有用法的情况下扩展React组件属性类型,reactjs,typescript,react-native,Reactjs,Typescript,React Native,我想使testID成为一个可用于所有React.Component本地测试实例的道具。目前,我正在将它添加到使用它的所有组件的道具类型中。例如,是否有任何方法可以定义react/index.d.ts并覆盖组件属性类型以包括{testID?:string} 编辑: //类型/react/index.d.ts 导入“反应” 从“react”导入{Attributes,ClassAttributes} 声明命名空间反应{ 接口内部属性扩展属性{ testID?:字符串 } 接口IntrinsicCla

我想使
testID
成为一个可用于所有
React.Component
本地测试实例的道具。目前,我正在将它添加到使用它的所有组件的道具类型中。例如,是否有任何方法可以定义
react/index.d.ts
并覆盖组件属性类型以包括
{testID?:string}

编辑:

//类型/react/index.d.ts
导入“反应”
从“react”导入{Attributes,ClassAttributes}
声明命名空间反应{
接口内部属性扩展属性{
testID?:字符串
}
接口IntrinsicClassAttributes扩展了ClassAttributes{
testID?:字符串
}
}

我尝试了上面的覆盖,但它不起作用,但如果我复制整个react键入文件,然后进行上述更改,它就可以正常工作。所以我只需要适当的覆盖技术。有人能帮我吗?

对于类组件,创建一个代理类,并在继承静态属性时对其进行扩展:

class Proxy extends React.Component {
  static propTypes = {
    testId: PropTypes.string
  };
}

class SomeComponent extends Proxy {
  render() {

  }
}
对于功能组件,您不能这样做。另一种方法是创建一个实用程序,为您添加:

function withPropTypes(Component) {
    Component.propTypes = {
        testId : PropTypes.string
    };

    return Component;
}


function SomeComponent() {

}

const SomeComponentWithPropTypes = withProps(SomeComponent);
注意:您也可以将上述util用于类组件。

//src/types/react/index.d.ts
// src/types/react/index.d.ts

import * as React from 'react'

declare global {
  namespace JSX {
    interface IntrinsicAttributes extends React.Attributes {
      testID?: string
    }

    interface IntrinsicClassAttributes<T> extends React.ClassAttributes<T> {
      testID?: string
    }
  }
}
从“React”导入*作为React 宣布全球{ 名称空间JSX{ 接口内部属性扩展了React.Attributes{ testID?:字符串 } 接口IntrinsicClassAttributes扩展了React.ClassAttributes{ testID?:字符串 } } }

这对我来说很有用。谢谢大家

这是我在问题中所关心的,我不想改变组件的用法。我不能以某种方式更改我自己的React声明文件。
// src/types/react/index.d.ts

import * as React from 'react'

declare global {
  namespace JSX {
    interface IntrinsicAttributes extends React.Attributes {
      testID?: string
    }

    interface IntrinsicClassAttributes<T> extends React.ClassAttributes<T> {
      testID?: string
    }
  }
}