2017-06-05 27 views
1

使用Flow,我希望能够为功能反应组件指定一个界面,该界面定义组件作为属性使用的几个方法。Flow - 基于反应组件的道具定义界面

我想让包装器组件能够在实现这些属性的子组件上设置这些属性。

下面是代码我现在有:

interface Updateable { 
    update(string): void 
}; 

const Edit = ({ 
    update 
}: { 
    update: string => void 
}) => <a onClick={e => update(e.target.value)}>Something</a> 

const UpdateContainer = ({ toRender }: { toRender: Updateable }) => (
    <toRender update={message => alert(message)} /> 
) 

const Wrapper = (
    <UpdateContainer toRender={Edit} /> 
); 

这给我的错误:

const UpdateContainer = ({ toRender }: { toRender: Updateable }) => (

update of Updateable. Property not found in <UpdateContainer toRender={Edit} />

如何指定的接口基于反应组件属性?或者除了我应该使用的界面之外还有其他的东西吗?

回答

0

Playground

type Updateable = { 
    update: (value: string) => void 
}; 

const Edit = ({ 
    update 
}: Updateable) => <a onClick={e => update(e.target.value)}>Something</a> 

const Foo = ({ 
    foo 
}: { 
    foo: string => void 
}) => <a onClick={e => foo(e.target.value)}>Something</a> 

const UpdateContainer = ({ toRender }: { toRender: (props: Updateable) => React$Element<any> }) => (
    <toRender update={message => alert(message)} /> 
) 

const Wrapper1 = (
    <UpdateContainer toRender={Foo} /> 
); 

const Wrapper2 = (
    <UpdateContainer toRender={Edit} /> 
); 

有了这个代码,Wrapper1生成错误但Wrapper2没有。我将接口切换为一种类型,因为我对flowtype中的接口并不熟悉。

至于问题,问题是这部分{ toRender: Updateable }

{ toRender: Updateable } states toRender是实现Updateable的东西,但是当传递Edit时不是这种情况。

Edit是一个函数,其参数为props,它是那些实施Updateable的道具。

我将代码更改为{ toRender: (props: Updateable) => React$Element<any> }以反映此(并将接口切换为前面提到的类型,我不确定是否需要这些,这只是我知道的方式)。

我希望这会有所帮助。