我有一个react HoC,其中我定义了几个状态,并将其传递给包装的组件.但包装组件本身有一些props .

Hoc.tsx公司

const HOC = (Component: React.ComponentType<T>) => {
  const [someState, setSomeState] = useState()

  const WrappedComponent = (props: T) =>
    return(
      <Component {(...props) as T} someState={someState}/>
    )

  return WrappedComponent
}

在需要其他props 的组件中的临时用法

interfae NewComponentProps {
  x: number
}

const NewComponent: React.FC<NewComponentProps> = (props) => {
  let {x, someState} = props

  //Here I am not able to access someState prop which is coming from HOC, typescript is giving error
  return ( ... )
}

export default HoC(NewComponent)

如何处理这种情况,如果我在NewcomComponentProps接口中添加sometState,它将起作用,但当我在任何地方调用NewComponent时,我必须传递sometState prop

So what should be the props type of new component to access both props??

推荐答案

下面是一个小示例,说明如何键入它以使其工作

type WrappedProps = {
  b: string;
};
// Here you type the child component as generic T combined with 
// your Wrapped props
const Wrapped = <T,>(Comp: ComponentType<T & WrappedProps>) => {
  return (props: T) => {
    return <Comp {...props} b="World" />;
  };
};

// ============================

type CompProps = {
  a: string;
};
// You need to manually pass the props of your component to the Wrapped
// function, because it can't infer the type
const Comp = Wrapped<CompProps>((props) => {

  // props now has the type CompProps & WrappedProps
  return (
    <p>
      A: {props.a}
      <br />
      B: {props.b}
    </p>
  );
});

// ============================

export default function App() {
  return <Comp a="Hello" />;
}

Javascript相关问答推荐

如何在使用fast-xml-parser构建ML时包括属性值?

当在select中 Select 选项时,我必须禁用不匹配的 Select

使用复选框在d3.js多折线图中添加或删除线条

使搜索栏更改语言

康威的生活游戏规则在我的Javascript版本中不起作用.''我做错了什么?

如何从URL获取令牌?

在Three JS中看不到补间不透明度更改效果

如何控制Reaction路由加载器中的错误状态?

以Angular 实现ng-Circle-Progress时出错:模块没有导出的成员

从另一个数组中的对应行/键值对更新数组中的键值对对象

为什么当我更新数据库时,我的所有组件都重新呈现?

输入的值的类型脚本array.排序()

Node.js错误: node 不可单击或不是元素

JAVASCRIPT SWITCH CASE语句:当表达式为';ALL';

在HTML5画布上下文中使用putImageData时,重载解析失败

如何在每隔2分钟刷新OKTA令牌后停止页面刷新

使用Java脚本筛选数组中最接近值最小的所有项

带元素数组的Mongo聚合

与find()方法一起使用时,Mongoose中的$or运算符没有提供所有必需的数据

从C#的Angular 来看,Java回调基础知识