gpt4 book ai didi

javascript - 如何在 React.CreateClass 中为对象属性提供流类型提示

转载 作者:太空宇宙 更新时间:2023-11-04 16:20:51 24 4
gpt4 key购买 nike

我有一些使用 React.createClass 创建的组件的 React 代码。

某些组件将对象上的内容存储为普通属性,例如this.foothis.props.foothis.state.foo 相对。

有什么方法可以向 Flow 提供有关“foo”属性的提示吗?我现在想避免重写这些组件。

最佳答案

您可以为传递给 createClass 的对象提供显式类型。类似的东西

/* @flow */

import React from 'react';

type Spec = { foo: string };

const spec: Spec = {
foo: 'bar',
render() {
return <div>{this.foo}</div>;
}
}

const MyComponent = React.createClass(spec);

或者如果您更喜欢保持类型内联,只需使用强制转换

/* @flow */

import React from 'react';

const MyComponent = React.createClass(({
foo: 'bar',
render() {
return <div>{this.foo}</div>;
}
}: { foo: string }));

要证明此方法有效,请尝试将 foo 设置为 42。 Flow 会提示

/* @flow */

import React from 'react';

const MyComponent = React.createClass(({
foo: 42, // <-- error: number. This type is incompatible with string
render() {
return <div>{this.foo}</div>;
}
}: { foo: string }));

关于javascript - 如何在 React.CreateClass 中为对象属性提供流类型提示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40658744/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com