2017-10-17 60 views
0

我想從React組件繼承,並定義新的Props。類似的東西(有很多的錯誤與Bar,應該完全是錯誤的):flowtype:繼承和通用

// @flow 

class Component<Props> { 
    props: Props; 

    constructor(props: Props) { 
     this.props = props; 
    } 
} 

type FooProps = { 
    x: number; 
} 

class Foo extends Component<FooProps> { 
    _render(value: string) { 
     return `hello, ${value}`; 
    } 
    render() { 
     return this._render(`${this.props.x}`); 
    } 
}; 

type BarProps = { 
    x: number; 
    y: number; 
} 

class Bar extends Foo<BarProps> { 
    render() { 
     return this._render(`${this.props.x} ${this.props.y}`); 
    } 
} 

const foo: Foo = new Foo({x: 1}); 
const bar: Bar = new Bar({x: 1, y: 2}); 

我應該如何使用仿製藥流與繼承? (在React組件的上下文中,如果它很重要的話)。

使用流程0.57.2並作出反應16.0.0

+0

你是什麼意思繼承?在使用'React'的情況下,輸入組件時繼承不起作用。你只需要像'PropType'那樣輸入'props'' –

+0

意思是'Bar'擴展'Foo','Bar'改變'props'的類型。我會再想一想... –

回答

0

最簡單的情況下,創建一個新的反應成分,鍵入props看起來像這樣在ES:

// @flow 
import React from 'react' 

type Props = { books: Array<String>, search: (string) => void } 

class SearchList extends React.Component { 
    static defaultProps: Props 
    props: Props 

    render() { /*...*/ } 
} 

SearchList.defaultProps = { books: [], search: (_) => undefined } 

編輯:忘了這是使用class fields建議,在舞臺3.如果您提正在使用像create-react-app這樣的引導程序,您可以使用它。否則你可以這樣做:

// @flow 
import React from 'react' 

type Props = { books: Array<String>, search: (string) => void } 

class SearchList extends React.Component<Props> {  
    render() { /*...*/ } 
} 
+0

這給了「錯誤」(流量0.57.2&反應16):屬性「組件」。類型參數太少。預計至少1.這就是爲什麼我想要像這裏描述的 https://flow.org/en/docs/react/components/ –

+0

是的第一個例子是使用新的類字段。你需要使用一個'babel'插件來訪問這些插件。第二個應該沒有這個工作 –

+0

你的意思是需要使用'babel'插件,並將其輸出到'flow'? –