我想继承一个React组件,并定义新的Props。类似这样的东西( Bar有很多错误,应该是完全错误的):
// @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组件的上下文中,如果重要的话)。
使用flow 0.57.2和react 16.0.0。
发布于 2017-10-17 15:37:35
最简单的情况是,在ES中创建一个新的react组件并键入props如下所示:
// @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 }编辑:忘记提到这是使用阶段3中的class fields建议。如果您使用的是像create-react-app这样的引导程序,则可以使用它。否则,您可以执行以下操作:
// @flow
import React from 'react'
type Props = { books: Array<String>, search: (string) => void }
class SearchList extends React.Component<Props> {
render () { /*...*/ }
}https://stackoverflow.com/questions/46784510
复制相似问题