流类型:带有克隆元素的HOC



我正在尝试创建一个更高阶的组件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>;
}

这个问题我没有答案,但是我有一个变通办法。

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' />;
}

不错,没有错误

最新更新