流类型:带有cloneElement的HOC

时间:2016-08-19 17:34:44

标签: flowtype

我正在尝试创建一个更高阶的组件Hoc,它通过React.cloneElement为其子代提供一些额外的道具。我无法让flowtype知道额外的道具实际上是传下来的。

下面是我失败的尝试,它抛出了在对象文字上找不到的错误foo类型。我想知道我能做些什么来解决这个问题。

type Props = {
  foo: string,
  bar: string,
};

type DefaultProps = {
  foo: string,
};

declare class React2$Element<Config, DP> extends React$Element{
  type: _ReactClass<DP, *, Config, *>;
}


declare function Hoc<Config, DP: DefaultProps, R: React$Element<Config>>(props: {children: R}) : React2$Element<Config, DP>

function TestComponent({foo, bar}: Props){
  return <div>{bar}</div>;
}


function Hoc(props){
  return React.cloneElement(props.children, {foo: 'form2wr'});
}


function Test(){
  return <Hoc children={<TestComponent bar='yo' />}></Hoc>;
}

1 个答案:

答案 0 :(得分:0)

我对这个问题没有答案,但我确实有一个解决方法。

type Props = {
  foo: string,
  bar: string,
};

type DefaultProps = {
  foo: string,
};

type WithHOCProps<X> = $Diff<X, DefaultProps>

declare function TestComponent(props: WithHOCProps<Props>) : React$Element;

function TestComponent({foo, bar}: Props){
  return <div>{foo + bar}</div>;
}


function Test(){
  return <TestComponent bar='yo' />;
}

Tadahhh,没有错误。

相关问题