Iva*_*nák 6 typescript reactjs flowtype
我有反应码
export default class MyComponent extends Component<Props,State>
问题是,我会写像a type或an 这样的道具interface吗?
type Props = {
isActive: Boolean,
onClick: Function
}
Run Code Online (Sandbox Code Playgroud)
要么
interface Props {
isActive: Boolean,
onClick: Function
}
Run Code Online (Sandbox Code Playgroud)
另外,当我不使用打字稿,而是使用经典的webpack + babel设置时,方向是什么?
或者,它甚至对我有多重要?
for*_*d04 22
现在是 2020 年,type在几乎所有使用React道具的情况下,我都会赞成(此处为通用类型与界面帖子)。只能用类型别名表示的常见情况:
// given some props from another comp that are to be altered
type ExternalProps = { a: string; b: { c: number } };
type Props_IndexType = ExternalProps["b"]; // { c: number; }
type Props_MappedType = { [K in keyof ExternalProps]: number }; // { a: number; b: number; }
type Props_DiscriminatedUnionType = { tag: "tag1"; foo: string } | { tag: "tag2"; foo: boolean}
type Props_typeOf = { foo: string } & typeof defaultProps; // see class comp example
// conditional types - ok, this one is a bit contrived, but you get the point
type Props_ConditionalType<T> = T extends true ? { a: string } : { b: number };
const Comp = <T extends {}>(props: Props_ConditionalType<T>) =>
<div>{"a" in props && (props as any).a}</div>
render(<Comp<true> a="foo" />, document.getElementById("root"));
Run Code Online (Sandbox Code Playgroud)
用于说明的类组件示例(OP 提到了它们,但上述情况也适用于 Hook):
// cannot do that with interfaces
type Props = ({ tag: "tag1"; foo: string } | { tag: "tag2"; foo: boolean }) &
typeof defaultProps;
type State = typeof initState;
const defaultProps = { a: "A" };
const initState = { c: "C" };
class App extends React.Component<Props, State> {
static readonly defaultProps = defaultProps;
state = initState;
render() { ... }
}
render(<App tag="tag1" foo="foo" />, document.getElementById("root"));
Run Code Online (Sandbox Code Playgroud)
唯一的情况,我会考虑接口:
| 归档时间: |
|
| 查看次数: |
3346 次 |
| 最近记录: |