Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/24.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Reactjs HOC注入的功能组件道具的类型安全处理_Reactjs_Typescript_React Props_High Order Component - Fatal编程技术网

Reactjs HOC注入的功能组件道具的类型安全处理

Reactjs HOC注入的功能组件道具的类型安全处理,reactjs,typescript,react-props,high-order-component,Reactjs,Typescript,React Props,High Order Component,TL;DNR:我正在使用TypeScript 3.3.3。有没有更好的方法来声明从HOC注入的我需要的道具,而不使它们对使用我的组件的代码可见 考虑一个用withNamespacesHOC修饰的基本组件。使用的库和HOC是任意的,我在使用任何遵循此模式的组件时都遇到了这个问题。类组件也有点问题,但这里我将重点介绍函数 // MyComponent.tsx import * as React from 'react' import { withNamespaces, WithNamespaces

TL;DNR:我正在使用TypeScript 3.3.3。有没有更好的方法来声明从HOC注入的我需要的道具,而不使它们对使用我的组件的代码可见


考虑一个用
withNamespaces
HOC修饰的基本组件。使用的库和HOC是任意的,我在使用任何遵循此模式的组件时都遇到了这个问题。类组件也有点问题,但这里我将重点介绍函数

// MyComponent.tsx
import * as React from 'react'
import { withNamespaces, WithNamespaces } from 'react-i18next'


const MyComponent: React.FunctionalComponent = ({ children, t }) => (
  <a title={t('my translated text')}>{children}</a>
)

export default withNamespaces('my-component')(MyComponent)
现在
MyComponent
编译并为我可能的道具提供了很好的类型安全性。然而,现在我的测试文件很生气,因为我没有提供组件定义期望的道具值,例如
t
。然而,我们知道这将被HOC注入,因此创建一个mock或为这个prop提供一些垃圾值只是混淆和不必要的额外工作来修复类型问题

// type is missing the following properties from WithNamespaces: t, etc., etc.
const wrapper = shallow(<MyComponent>Test</MyComponent>)
不过,这有点粗俗和不雅。还有很多其他的方法,比如强制转换到任何不引用名称空间的对象,等等,但是肯定有更好的方法吗

杂项


withNamespace
确实有一个定义,它使用从返回的类型中排除
withNamespace
中的道具,但这似乎不起作用,至少对功能组件是这样。

您使用的是什么版本?我刚刚安装了
react-i18next
“@types/react”:“^16.8.8”、“i18next”:“^15.0.7”、“react”:“^16.8.4”、“react-i18next”:“^10.5.2”
)的定义,它可以按预期工作(
t
)@TitianCernicova Dragomir我一直在关注最新消息-i18next@9因为我正在使用next-i18next与NextJS集成,它们还不支持10。然而,我在使用其他HOC时遇到了同样的问题,例如材质UI的
和样式
。您使用的是什么版本?我刚刚安装了
react-i18next
“@types/react”:“^16.8.8”、“i18next”:“^15.0.7”、“react”:“^16.8.4”、“react-i18next”:“^10.5.2”
)的定义,它可以按预期工作(
t
)@TitianCernicova Dragomir我一直在关注最新消息-i18next@9因为我正在使用next-i18next与NextJS集成,它们还不支持10。然而,我在使用其他HOC时遇到了同样的问题,例如材质UI的
和样式
 const MyComponent: React.FunctionalComponent<WithNamespaces> = ({children, t}) => ( // ...
// type is missing the following properties from WithNamespaces: t, etc., etc.
const wrapper = shallow(<MyComponent>Test</MyComponent>)
const MyComponent: React.FunctionalComponent = (props) => {
  const { children, t } = props as WithNamespaces
  return (
    <a title={t('my translated text')}>{children}</a>
  )
}