Reacts `propTypes` 和 `defaultProps` 应该与 Flowtype 结合使用,还是 Flowtype 足够全面?
Should Reacts `propTypes` and `defaultProps` be used in conjunction with Flowtype, or is Flowtype comprehensive enough?
想到一个简单的例子如:
class CommentAreaComponent extends React.Component {
static propTypes = {
id: PropTypes.string.isRequired,
loading: PropTypes.bool,
};
static defaultProps = {
loading: false,
};
在构造函数中我可以定义这样的东西来实现(我认为)同样的事情:
class MyComponent extends React.Component {
constructor({
loading = false,
}:{
id:string,
loading?:boolean
}) {
super(arguments[0]);
}
}
第二个示例仅使用 Flowtype。使用 Reacts PropTypes 和 DefaultProps 有优势吗?或者我可以在使用 FlowType 时完全放弃它们吗?
您当然可以使用 Flow 类型而不是 React PropTypes,但您建议的语法不是常用的方法。请参阅 Flow docs(向下滚动以了解 ES6 语法):
class Button extends React.Component {
props: {
title: string,
visited: boolean,
onClick: () => void,
};
state: {
display: 'static' | 'hover' | 'active';
};
static defaultProps = {
visited: false,
};
constructor(props) {
super(props);
this.state = {
display: 'static',
};
}
render() {
let className = 'button ' + this.state.display;
if (this.props.visited) {
//...
}
return (/*...*/);
}
}
您可以使用 PropTypes 做的唯一不能用 Flow 类型做的事情是定义 custom validators(例如检查 prop 是否是有效的电子邮件)。
我有更多 Flow React examples on github,但我还没有用 Flow v0.22 测试它们,只有 v0.21。他们可能需要稍作调整。
一般来说,Flow 的静态分析将为您提供更强大的功能和更大的影响力,因此优于 propTypes
。
然而,propTypes
在您可能通过多个组件向下传播对象道具的情况下,或者在道具可能没有您期望的值的其他动态运行时场景中仍然很好。
考虑通过 https://github.com/brigand/babel-plugin-flow-react-proptypes
充分利用两者
注意:我不隶属于该图书馆。
想到一个简单的例子如:
class CommentAreaComponent extends React.Component {
static propTypes = {
id: PropTypes.string.isRequired,
loading: PropTypes.bool,
};
static defaultProps = {
loading: false,
};
在构造函数中我可以定义这样的东西来实现(我认为)同样的事情:
class MyComponent extends React.Component {
constructor({
loading = false,
}:{
id:string,
loading?:boolean
}) {
super(arguments[0]);
}
}
第二个示例仅使用 Flowtype。使用 Reacts PropTypes 和 DefaultProps 有优势吗?或者我可以在使用 FlowType 时完全放弃它们吗?
您当然可以使用 Flow 类型而不是 React PropTypes,但您建议的语法不是常用的方法。请参阅 Flow docs(向下滚动以了解 ES6 语法):
class Button extends React.Component {
props: {
title: string,
visited: boolean,
onClick: () => void,
};
state: {
display: 'static' | 'hover' | 'active';
};
static defaultProps = {
visited: false,
};
constructor(props) {
super(props);
this.state = {
display: 'static',
};
}
render() {
let className = 'button ' + this.state.display;
if (this.props.visited) {
//...
}
return (/*...*/);
}
}
您可以使用 PropTypes 做的唯一不能用 Flow 类型做的事情是定义 custom validators(例如检查 prop 是否是有效的电子邮件)。
我有更多 Flow React examples on github,但我还没有用 Flow v0.22 测试它们,只有 v0.21。他们可能需要稍作调整。
一般来说,Flow 的静态分析将为您提供更强大的功能和更大的影响力,因此优于 propTypes
。
然而,propTypes
在您可能通过多个组件向下传播对象道具的情况下,或者在道具可能没有您期望的值的其他动态运行时场景中仍然很好。
考虑通过 https://github.com/brigand/babel-plugin-flow-react-proptypes
充分利用两者注意:我不隶属于该图书馆。